【发布时间】:2010-09-28 08:08:33
【问题描述】:
为了更好的理解,我在js中做了一些继承,发现了一些让我困惑的地方。
我知道,当您使用 new 关键字调用“构造函数”时,您会得到一个引用该函数原型的新对象。
我还知道,为了进行原型继承,您必须将构造函数的原型替换为您希望成为“超类”的对象的实例。
所以我做了这个愚蠢的例子来尝试这些概念:
function Animal(){}
function Dog(){}
Animal.prototype.run = function(){alert("running...")};
Dog.prototype = new Animal();
Dog.prototype.bark = function(){alert("arf!")};
var fido = new Dog();
fido.bark() //ok
fido.run() //ok
console.log(Dog.prototype) // its an 'Object'
console.log(fido.prototype) // UNDEFINED
console.log(fido.constructor.prototype == Dog.prototype) //this is true
function KillerDog(){};
KillerDog.prototype.deathBite = function(){alert("AAARFFF! *bite*")}
fido.prototype = new KillerDog();
console.log(fido.prototype) // no longer UNDEFINED
fido.deathBite(); // but this doesn't work!
(这是在 Firebug 的控制台中完成的)
1) 为什么如果所有新对象都包含对创建函数原型的引用,fido.prototype 是未定义的?
2) 继承链是 [obj] -> [constructor] -> [prototype] 而不是 [obj] -> [prototype] 吗?
3) 是否检查过我们对象 (fido) 的“原型”属性?如果是这样......为什么'deathBite'未定义(在最后一部分)?
【问题讨论】:
标签: javascript inheritance prototype prototypal-inheritance