Suppose I have an object, and create another object with it:
var person = {
name: "Lee",
age: "12",
others: {}
}
var per1 = Object.create(person);
var per2 = Object.create(person);
per2.name = "Mike";
per2.others.hello = "world";
console.log(per1); // Object {name: "Lee", age: "12", obj: Object}
console.log(per2); // Object {name: "Mike", name: "Lee", age: "12", obj: Object}
console.log(per1.others.hello, per2.others.hello) // world world
my confuse is:
Why the
per2have double name? If another is from prototype, I try toper2.prototype.name = "mike"it tell me the prototype is undefined, but how can that is undefined? The job ofObject.createisn'tCreates a new object with the specified prototype object and properties.MDNWhy the
otherswould shared betweenper1andper2but the name doesn't
Another confuse is suppose I have a function:
function Person(name) {
this.name = name
}
Person.prototype.say = function () {
console.log("hello")
}
but create an other object from the function, no the prototype of the function:
var obj = Object.create(Person);
console.log(obj) // Function {}:
console.log(obj.prototype) // undefined
Why the prototype is undefined? Doesn't the Object.create create it?
Update:
As @bfavaretto said only the constructor can have prototype, and the Object.getPrototypeOf can show one object's prototype.So I tried these two approach to get the per1's prototype:
console.log(per1.constructor.prototype) // Object{}
console.log(Object.getPrototypeOf(per1)) //Object {name: "Lee", age: "12", obj: Object}
they are different, why?
Object.createin JavaScript.