[英]during prototypal inheritance in js, i am getting undefined when i am trying to access the method of inherited object
var animal = {eats:true};
var rabbit = {jumps:true};
rabbit.prototype = animal;
document.write(rabbit.eats);
i am trying prototypal inheritance but this gives the answer as undefined, rather it should be true.我正在尝试原型继承,但这给出了未定义的答案,而应该是真的。 i am doing it on IE9
我是在 IE9 上做的
prototype
is a reference object defined on classes rather than objects in JavaScript, you need to define a class and set up an inheritance using prototype
: 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
Or better if you define both entities as classes:或者将两个实体都定义为类会更好:
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
There's an undocumented __proto__
object in Gecko browsers, like google chrome, that lates you fool the prototype chain and statically inherit an object from another:在 Gecko 浏览器中有一个未记录的
__proto__
对象,比如谷歌浏览器,它迟到了你愚弄原型链并从另一个静态继承一个对象:
var animal = {eats:true};
var rabbit = {jumps:true};
rabbit.__proto__ = animal;
rabit.jumps; // true
rabit.eats; // true
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.