注:本文为译文,原文出处Javascript Object Layout
function Foo() { } ;
var f1 = new Foo();
Foo.prototype.x = "hello";
f1.x //=> hello
Foo.x //=> undefined
注意, 函数Foo创建的对象, 需要通过Foo.prototype给来设置属性, 并不是通过f1.prototype设置f1的属性. 这是非常需要注意的一点.
function foo() { } ; var f1 = new foo();
f1.constructor === foo.prototype.constructor === foo
//replace the default prototype object
foo.prototype = new Object();
//create another instance l
f1 = new foo();
//now we have:
f1.constructor === foo.prototype.constructor === Object
//so now we say:
foo.prototype.constructor = foo
//all is well again
f1.constructor === foo.prototype.constructor === foo
function foo() { }
f1 = new foo();
f2 = new foo();
foo.prototype.x = "hello";
f1.x => "hello"
f2.x => "hello";
f1.x = "goodbye"; //setting f1.x hides foo.prototype.x
f1.x => "goodbye" //hides "hello" for f1 only
f2.x => "hello"
delete f1.x
f1.x => "hello"; //foo.prototype.x is visible again to f1.
设置对象原型的属性会导致所有实例的变化.
foo.prototype.x = "goodbye";
//now
f1.x => "goodbye"
f2.x => "goodbye";
观察上图中的不同的箭头, 会看到javascript语言中一些有趣的关系。 (如果想试一试, 可以在javascript控制台输入以下代码样例)。
f1.toString() 调用:
Object.prototype.toString
输出结果: [object ...]
而:
Foo.toString() 优先查找:
Function.prototype.toString()
输出结果: [Function foo...]
如果这样:
delete Function.prototype.toString
Foo.toString()
输出结果: [object ...]