【问题标题】:When defining function on a prototype, is the function recreated on each new instance?在原型上定义函数时,是否在每个新实例上重新创建函数?
【发布时间】: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() 时重新创建myFunctionmyFunction2,或者新的TestClass() 是否包含指向原始myFunctionmyFunction2? 的指针

【问题讨论】:

  • 不,原型是共享对象。
  • 原型继承的工作方式是创建一个对象链来进行属性解析。您的 tctc2 对象将没有(拥有)myFunction 属性,因此将在其“原型链”中搜索该属性。该链中的第一个对象将是TestClass.prototype 对象,它将在其中找到属性并返回函数。从TestClass 构造函数创建的所有对象都将TestClass.prototype 作为其原型链中的第一个对象。

标签: javascript prototype


【解决方案1】:

您使用 TestClass 函数作为构造函数创建的每个对象,例如

var test1 = new TestClass();
var test2 = new TestClass();

将具有相同的原型。当您尝试调用该函数时会发生什么:

test2.myFunction2();

是JS解释器会在test2引用的对象上查找myFunction2。它没有 myFunction2 属性,因此它查找链以查看 test2 的原型是否具有名为“myFunction2”的函数类型的属性 - 它确实存在,因此它调用它。

所以回答这个问题:

或者新的 TestClass() 是否包含指向原始 myFunction 和 myFunction2 的指针?

您使用 new TestClass() 创建的对象将包含对一个对象(它是原型)的引用,并且该对象包含对这两个函数的引用。请注意,新对象与其原型之间的引用是保密的,请参阅:

here

这可能会导致极度混乱,因为有两个东西叫做“原型” - 有一个构造函数的属性叫做“原型”,还有一个秘密链接(例如 proto 在 webkit 中)。在代码中似乎比写下来容易得多:

var TestClass = function() {}
TestClass.prototype = {
   method: function() {}
};

var a = new TestClass();
console.log(a.__proto__ === TestClass.prototype); // true
console.log(a.method === TestClass.prototype.method); // true

【讨论】:

  • 完美。这就是我的怀疑,但我想确定一下。谢谢你的回答,我会尽快标记。
  • +1 虽然我强调对其原型的引用是隐式/内部引用。人们有时认为他们可以通过test1.prototype 获得直接参考。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-07
  • 1970-01-01
  • 2016-08-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多