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.