At the moment, I try to understand the Javascript prototype object. Following situation:
// new Person object
function Person () {
this.greeth = function() {
console.log("Good morning, " + this.name);
};
};
// add new function to Person.prototype for inheritance
Person.prototype.sayWeight = function() {
console.log(this.weight);
};
// create new friend object
var friend = {
forename: "Bill",
lastname: "Gates",
weight: 78,
sayhello: function() {
console.dir("Hello " + this.forename + ' ' + this.lastname);
}
};
// assign Person.prototype to friend.prototye (inheritance)
friend.prototype = Person;
console.dir(friend);
Now my question:
I assign the Person Object to my friend.prototype .
For my understanding, "friend" should have all the functions of Person.prototype (i.e. sayWeight() cause of friend.prototype = Person; ).
But the only function I can call is friend.sayhello.
In my output (console.dir(friend);), I can see the sayWeight() function, but when I call it, I get an error (TypeError: Object #<Object> has no method 'sayWeight')
Can you explain this behavior? Why can't I access the sayWeight() function?
=========================================================
Another question:
function Person() {
this.name = "Bill Gates";
this.weight = 78;
this.sayHello = function() {
console.log("Hello " + this.name);
}
}
Person.prototype.sayWeight = function() {
console.log(this.weight);
}
var friend = new Person();
What is the difference between the sayWeight and the sayHello function? The sayWeight function is in the prototype-object of Person - okay, but what advantages do I have from prototype in this case?
x.prototypeis not "the prototype of x".