简体   繁体   English

在js中的原型继承期间,当我尝试访问继承对象的方法时,我变得未定义

[英]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.

相关问题 我得到:尝试访问javascript clas中的对象时,无法调用未定义的方法“ someMethodName” - I am getting: Cannot call method 'someMethodName' of undefined when trying to access an object in a javascript clas 当对象非常多并且试图在范围内访问它时,为什么会出现“无法读取未定义的属性0”的信息? - Why am I getting “Can not read property 0 of undefined”, when the object is very much there and I am trying to access it within scope? 当我尝试调用我的方法时,为什么我会变得不确定? - Why am I getting undefined when I am trying to call my method? JavaScript原型继承混乱 - 我在这里缺少什么? - JavaScript prototypal inheritance confusion - what am I missing here? 为什么当我尝试访问我在 node.js 中的财产时,我变得不确定 - why I am getting undefined when I try to access on my property in node js 尝试访问嵌入的Google地图时,为什么会出现无法读取未定义的属性“ getCenter”的问题? - Why am I getting Cannot read property 'getCenter' of undefined when trying to access my embed google map? 为什么我在 Discord.js 中尝试获得公会时得到未定义的信息? - Why am I getting an undefined when trying to get a Guild in Discord.js? 为什么我变得未定义不是Vue JS中的对象错误 - Why am I getting undefined is not an object error in vue js 当它明显是我正在使用的对象的原型时,JS函数未定义 - JS Function undefined when it is clearly a prototype of the object I am using 尝试编写Javascript对象时出现意外错误 - I am getting an unexpected error when trying to write a Javascript object
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM