在这段代码中:
var Fruit = function() {}
Fruit.prototype = {
color: function () {
console.log('Fruit color...')
}
}
var Apple = function () {}
Apple.prototype = new Fruit()
Apple.prototype.constructor = Apple
var a = new Apple()
Apple.prototype = null // the question!!!
a.color()
当 Apple.prototype
被设置为 null
时,为什么实例 a
仍然可以调用 color
方法?
最佳答案
在创建实例 a
之后,您将更改 Apple.prototype
引用。
在此处更改引用不会更改现有实例。
你还会发现
var a = new Apple();
Apple.prototype = {}; // some other object
a instanceof Apple; // false
即因为我们改变了 Apple 的继承链 a
不再被视为 Apple。
设置 Foo.prototype = null
如果您尝试检查 instanceof Foo
将导致 TypeError
更改对象的属性不会更改对该对象的引用。例如
var foo = {},
bar = foo;
foo.hello = 'world';
foo === bar; // true
改变对象本身会改变引用
foo = {hello: 'world'};
foo === bar; // false
或者以更接近如何从实例引用原型(prototype)的方式编写,
var Foo = {}, // pseudo constructor
bar = {},
baz = {};
var fizz = {}; // fizz will be our pseudo instance
Foo.bar = bar; // pseudo prototype
fizz.inherit = foo.bar; // pseudo inheritance
Foo.bar = baz; // pseudo new prototype
fizz.inherit === foo.bar; // false, instance inheritance points elsewhere
当前设置继承链的最佳实践不是使用new
,而是使用Object.create
。
Apple.prototype = Object.create(Fruit.prototype);
如果您需要在 Apple 实例上调用 Fruit
构造函数,您可以这样做
function Apple() {
// this instanceof Apple
Fruit.apply(this);
// ...
}
关于javascript - 你能帮忙澄清一下Javascript原型(prototype)继承方法调用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31258775/