i have 2 objects, human and sam, with 2 given properties each
var human = {
legs: 2,
group: "mammal"
}
var sam = {
age: 23,
married: true
}
Can I attach the human object to the prototype of sam so that the properties of human are delegated to sam, and the sam object remains intact.
The desired result:
console.log(sam.legs); //=> 2
One way i am aware of (but i know is "bad practice") is to use the __proto__
property:
var sam = {
age: 23,
married: true,
__proto__: human // *NOT IDEAL*
}
or
sam.__proto__ = human; // *NOT IDEAL*
I am aware of Object.create()
but i do not know how to implement it without erasing everything that is already stored in the sam variable
var human = {
legs: 2,
group: "mammal"
}
var sam = {
age: 23,
married: true
}
sam = Object.create(human);
console.log(sam.age); //=> undefined
I know that I can just attach the human object to sam FIRST, and THEN assign properties to sam:
var human = {
legs: 2,
group: "mammal"
}
var sam = Object.create(human);
sam.age = 23;
married: true;
...but the whole point of my question is if i attach two objects, using the prototype property, that already have their own properties? Can i use Object.create() in a way that I'm not aware of?
I must have read everything on the first page of google results for object.create()
and i never saw the right type of examples
EDIT: I don't want to just copy properties over because i am working on a game and i don't want the changes to be permanent. Let's say that sam
has the human
prototype, but at any minute in the game, his prototype could change to zombie
or whatever.