简体   繁体   中英

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

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 :

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:

var animal = {eats:true};
var rabbit = {jumps:true};

rabbit.__proto__ = animal;
rabit.jumps; // true
rabit.eats; // true

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM