目前,我尝试理解 Javascript 原型对象。以下情况:
// 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);
现在我的问题是:我将 Person 对象分配给我的friend.prototype
. 据我了解,“ friend
”应该具有Person.prototype
(即sayWeight()
原因friend.prototype = Person;
)的所有功能。但我唯一可以调用的函数是friend.sayhello。在我的输出 ( console.dir(friend);
) 中,我可以看到该sayWeight()
函数,但是当我调用它时,我得到一个错误 ( TypeError: Object #<Object> has no method 'sayWeight'
)
你能解释一下这种行为吗?为什么我无法访问该sayWeight()
功能?
==================================================== =======
另一个问题:
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();
sayWeight
和函数有什么区别sayHello
?该sayWeight
函数位于 Person 的原型对象中 - 好的,但在这种情况下,原型有什么优势?