BlueElixir
BlueElixir

Reputation: 3409

Creating functions in function prototypes for Javascript

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.

Upvotes: 1

Views: 71

Answers (3)

skay-
skay-

Reputation: 1576

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();

Upvotes: 0

Oleksandr T.
Oleksandr T.

Reputation: 77482

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

Upvotes: 4

Shikiryu
Shikiryu

Reputation: 10219

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

Upvotes: 0

Related Questions