简体   繁体   English

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

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

I am using the following code: 我正在使用以下代码:

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

My question is: when I set Tmp.prototype = null; 我的问题是:当我设置Tmp.prototype = null时; why it has no effect to tmp.f1(). 为什么它对tmp.f1()没有影响。 In other words, the tmp.f1() still output the same result. 换句话说,tmp.f1()仍输出相同的结果。 My understanding is that tmp.f1() will recursively check the property within the prototype chain and if the method is available, then the method is called. 我的理解是tmp.f1()将递归检查原型链中的属性,如果该方法可用,则将调用该方法。 But by setting Tmp.prototype = null, I expect that tmp.f1 will be undefined, but it's not the case. 但是通过设置Tmp.prototype = null,我希望tmp.f1是不确定的,但事实并非如此。

Thanks. 谢谢。

Probably the best reference in the specification is to 9.1.14 OrdinaryCreateFromConstructor . 规范中最好的参考是9.1.14 OrdinaryCreateFromConstructor

However, you can test this yourself. 但是,您可以自己对此进行测试。

 // 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