-3

I am not able to understand why this code is not working. I am trying to understand the prototype in Javascript. If I am declaring a new function inside a function then why am I not able to call that function?

<script>
  function Person(first) {
    this.firstName = first;                  
  }

  Person.prototype.name=function() {
    this.addLastNameInner=function() {
    return this.firstName+" Appended last name";   
    }                
  }

  Person.prototype.name.addLastName=function() {
    return this.firstName+" Appended last name";    
  }

  var pr=new Person('john');
  alert(pr.name.addLastNameInner());//Not working
  alert(pr.name.addLastName());//working fine
</script>
pabloFdz
  • 157
  • 1
  • 11
localhost
  • 483
  • 4
  • 10
  • You're setting `name` to a function on to which you add the property `addLastName`. – Henrik Andersson Dec 11 '15 at 11:28
  • 2
    It's not clear what you're trying to achieve, but `addLastNameInner` won't exist until you call `name`, and even then it will be added to the `Person` instance, not as a property of the `name` function. – James Thorpe Dec 11 '15 at 11:28
  • have a look at https://stackoverflow.com/questions/15884096/organize-prototype-javascript-while-perserving-object-reference-and-inheritance and https://stackoverflow.com/questions/16502467/prototype-deep-scope-of-this-to-access-instances-scope – Bergi Dec 11 '15 at 11:31
  • Your code says *`.name` is a function that when called will create a new function `addLastNameInner` on `this`*. If you want `name` to be an object with properties, create it as an object with properties, not as a function. – deceze Dec 11 '15 at 11:31

2 Answers2

0

To make your code work, you need to change the way you declare name:

Person.prototype.name = {
  addLastNameInner: function() {
    return this.firstName+" Appended last name";   
  }
};
Person.prototype.name.addLastName = function() {
  return this.firstName + " Appended last name";    
};

Because, what you are doing as .name is that you are not initializing it with a new keyword. And it cannot be done that way. The .name must be an Object with the functions.

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
-1

There are some misconceptions about the scope of objects and functions in the code. I hope the below code is what you want.

    function Person(first) {
        this.firstName = first;
    }
    Person.prototype.name={
        addLastNameInner:function(pr){
              return pr.firstName+" Appended last name";   
        }
    }
    Person.prototype.name.addLastName=function(pr){
        return pr.firstName+" Appended last name";    
    }
    var pr=new Person('john');
    alert(pr.name.addLastNameInner(pr));//Working fine
    alert(pr.name.addLastName(pr));//working fine