【发布时间】:2014-06-03 04:17:05
【问题描述】:
我在 javascript 中有以下代码,但我不清楚以下原型的底层功能:
function TestClass()
{
}
var externalFunction = function() {
console.log("hit the function defined internally");
};
Object.defineProperty(TestClass.prototype, "myFunction", {
enumerable: false,
writable: false,
value: externalFunction
});
TestClass.prototype.myFunction2 = function() {
console.log("hit the function defined on the prototype");
}
var tc = new TestClass();
var tc2 = new TestClass();
console.log(tc.myFunction === tc2.myFunction);
console.log(tc.myFunction2 === tc2.myFunction2);
是否在定义新的TestClass() 时重新创建myFunction 或myFunction2,或者新的TestClass() 是否包含指向原始myFunction 和myFunction2? 的指针
【问题讨论】:
-
不,原型是共享对象。
-
原型继承的工作方式是创建一个对象链来进行属性解析。您的
tc和tc2对象将没有(拥有)myFunction属性,因此将在其“原型链”中搜索该属性。该链中的第一个对象将是TestClass.prototype对象,它将在其中找到属性并返回函数。从TestClass构造函数创建的所有对象都将TestClass.prototype作为其原型链中的第一个对象。
标签: javascript prototype