将函数原型设置为null对新创建的javascript对象没有影响

时间:2015-10-28 06:25:52

标签: javascript function

我使用以下代码:

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

感谢。

1 个答案:

答案 0 :(得分:0)

规范中最好的参考可能是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 
&#13;
&#13;
&#13;