1

How do I properly create a function within a function prototype? What I have is this:

    <body>
    <p id="demo"></p><script>
function person(first, last, age, eye) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    this.eyeColor = eye;
}
person.prototype.name = function() {
    return {
        myFunc: function() {
          this.firstName + " " + this.lastName;
       }
      }
};

var myFather = new person("John", "Doe", 50, "blue");

document.getElementById("demo").innerHTML =
"My father is " + myFather.name().myFunc; 
</script>

</body>

When I run this it returns "My father is function () { this.firstName + " " + this.lastName; }" , but I was expecting John Doe.

3
  • 1
    you're not calling myFunc, you're just returning the function itself. if you want to invoke myFunc, then it should myFather.name().myFunc() Commented Feb 9, 2015 at 19:30
  • What's a "function prototype"? Commented Feb 9, 2015 at 19:30
  • @MarcB: Yes, although even that wouldn't work Commented Feb 9, 2015 at 19:31

3 Answers 3

4

You need call function, add () to myFunc. In your example you added reference to internal function.

document.getElementById("demo").innerHTML = "My father is " + myFather.name().myFunc(); 

Also add return to myFunc. To get properties from parent scope - save reference to this

person.prototype.name = function () {
  var _this = this;

  return {
    myFunc: function () {
      return _this.firstName + " " + _this.lastName;
    }
  }
};

Example

Sign up to request clarification or add additional context in comments.

1 Comment

This solution works, Thanks! I guess my usage of 'this' was incorrect in the question.
0

Myfunc is a function. When you call it, call like myfunc()

Comments

0

You are not calling myFunc and also that function does not return anything. I find this cleaner and a better way to define the funciton prototype:

function Person(first, last, age, eye) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    this.eyeColor = eye;
}
Person.prototype = {
    name: function() {
          return this.firstName + " " + this.lastName;
       }
};

Note that name now returns return this.firstName + " " + this.lastName;.

Then simply:

document.getElementById("demo").innerHTML = "My father is " + myFather.name();

1 Comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.