var animal = {eats:true};
var rabbit = {jumps:true};
rabbit.prototype = animal;
document.write(rabbit.eats);
我正在尝试原型继承,但这给出了未定义的答案,而应该是真的。我在IE9上这样做
答案 0 :(得分:2)
prototype
是在类而不是JavaScript中的对象上定义的引用对象,您需要使用prototype
定义类并设置继承:
var animal = {eats:true};
function Rabit(){};
Rabit.prototype = animal;
Rabit.prototype.jumps = true;
var rabit = new Rabit();
rabit.jumps; // true
rabit.eats; // true
如果将两个实体定义为类,则更好:
function Animal(){};
Animal.prototype.eats = true;
function Rabit(){};
Rabit.prototype = new Animal();
Rabit.prototype.jumps = true;
var rabit = new Rabit();
rabit.jumps; // true
rabit.eats; // true
Gecko浏览器中有一个未记录的__proto__
对象,比如google chrome,它会让你愚弄原型链并静态地从另一个对象继承对象:
var animal = {eats:true};
var rabbit = {jumps:true};
rabbit.__proto__ = animal;
rabit.jumps; // true
rabit.eats; // true