繁体   English   中英

将函数原型设置为null对新创建的javascript对象无效

[英]Set function prototype to null has no effect to newly created javascript object

我正在使用以下代码:

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是不确定的,但事实并非如此。

谢谢。

规范中最好的参考是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 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM