Reputation: 1514
I am trying to add a height method but now when i call it without the ()
.
How can i use this it as a method the benji.height()
method?I mean with the Parenthesis at the end?
function Dog() {
this.tail = true;
this.height = 33;
}
var benji = new Dog();
var rusty = new Dog();
Dog.prototype.height = function() {
return "the height is " + this.height + " cms";
};
console.log(benji.height);
Upvotes: 3
Views: 31
Reputation: 2466
So you have height variable in both the place Object and object prototype. So according to prototype chain it will first lookup in Object and then its prototype.
Here
function Dog() {
this.tail = true;
this.height = 33;
}
height variable will store in object So it will find height which is not a function that a reason you are not able to call as benji.height();
So as other user suggest just change the name of function you can call it as you want.
Upvotes: 1
Reputation: 34199
You have a field named height
and you are trying to add a method called height
.
You need to give it an unambigious name and it will work.
function Dog() {
this.tail = true;
this.height = 33;
}
var benji = new Dog();
var rusty = new Dog();
Dog.prototype.getHeight = function() {
return "the height is " + this.height + " cms";
};
document.body.innerHTML = "<b>height:</b> " + (benji.height) + "<br/>";
document.body.innerHTML += "<b>getHeight():</b> " + benji.getHeight();
Upvotes: 1