【问题标题】:Set function prototype to null has no effect to newly created javascript object将函数原型设置为 null 对新创建的 javascript 对象没有影响
【发布时间】:2015-10-28 06:25:52
【问题描述】:

我正在使用以下代码:

function Tmp(){}
var tmp = new Tmp()
Tmp.prototype.f1 = function(){console.log("f1");}

tmp.f1() -> output: f1 
Tmp.prototype.f1 = function(){console.log("f1 update");}
tmp.f1() -> output: f1 update

//this is confusing
Tmp.prototype = null;
tmp.f1() -> output still: f1 update

我的问题是:当我设置 Tmp.prototype = null;为什么它对 tmp.f1() 没有影响。换句话说, tmp.f1() 仍然输出相同的结果。我的理解是 tmp.f1() 将递归检查原型链中的属性,如果该方法可用,则调用该方法。但是通过设置 Tmp.prototype = null,我预计 tmp.f1 将是未定义的,但事实并非如此。

谢谢。

【问题讨论】:

  • 因为 tmp 在创建时分配了它的[[Prototype]],所以如果你分配一个新对象作为构造函数的原型,任何创建的实例都没有关系点仍然引用旧的原型对象。您可以通过getPrototypeOf查看。
  • @RobG 能否提供一些链接,我可以在其中详细了解此内容以及如果我们以后必须更新原型该怎么办,有什么解决方法吗?
  • @aishwatsingh:看来以后要更新一个原型,就必须循环遍历原型对象的属性。我在示例中所做的是创建整个新对象,因此它不会产生任何影响,因为现有对象的原型仍然引用旧创建的对象
  • 也看看this question
  • 顺便说一句,将.prototype 设置为null 实际上不会创建以null 作为原型的实例(就像Object.create(null) 一样),它们将改为从Object.prototype 继承。

标签: javascript function


【解决方案1】:

规范中最好的参考可能是9.1.14 OrdinaryCreateFromConstructor

但是,您可以自己测试。

// Constructor, has a default prototype object that
// is a plain Object
function Foo(){}

// Instance has its internal [[Prototype]] set to the
// constructor's prototype when it's created
var foo = new Foo();

// See?
document.write(Object.getPrototypeOf(foo) === Foo.prototype); // true

// Keep reference to Foo.prototpye
var originalFooProto = Foo.prototype;

// Change Foo.prototype
Foo.prototype = {};

// Create another instance
foo2 = new Foo();

// Current Foo.prototype is not original
document.write('<br>' + (originalFooProto === Foo.prototype)) // false 

// foo's internal prototype is not Foo's new prototype
document.write('<br>' + (Object.getPrototypeOf(foo) === Foo.prototype)) // false 

// foo's internal prototype is still the old Foo.prototype
document.write('<br>' + (Object.getPrototypeOf(foo) === originalFooProto)) // true 

// foo2's internal prototype is the new Foo.prototype
document.write('<br>' + (Object.getPrototypeOf(foo2) === Foo.prototype)) // true 

【讨论】:

    猜你喜欢
    • 2016-03-11
    • 2018-11-22
    • 2013-11-15
    • 2011-02-16
    • 2015-03-24
    • 1970-01-01
    • 2012-02-09
    • 1970-01-01
    • 2014-04-25
    相关资源
    最近更新 更多