var Person = function(name, age){
return Object.create(Object.prototype, {
name: {
value: name | "",
writable: true,
enumerable: true,
configurable: true
},
age: {
value: age | "",
writable: true,
enumerable: true,
configurable: true
}
});
};
var Boy = function(name, age){
return Object.create(Person(name, age), {
gender: {
value: "male"
}
});
};
var p = Person("John", 28);
var b = Boy();
console.log(p.isPrototypeOf(b)); // false?
我试图了解 object.create 以及如何最好地使用它,避免使用构造函数的 new
关键字。到目前为止,我正在按照上面的方法处理它(尽管可能不是最好的方法,只是反复试验) - 并且发现如果我使用 object.create
我将不再能够检查 instanceof
和对象类型。
有人建议使用 isPrototypeOf 来检查 - 我做错了什么,因为上面的代码在检查时返回 false
。
有人能解释一下我哪里出了问题吗?我对 javascript 中的原型(prototype)继承还很陌生。
最佳答案
当然p不是b的原型(prototype)。
这是因为 Person
函数每次都会返回一个新的对象。
尝试以下操作
var Boy = function(person, name, age){
return Object.create(person, {
gender: {
value: "male"
}
});
};
var p = Person("John", 28);
var b = Boy(p);
assert(p.isPrototypeOf(b))
关于Javascript object.create 和 isPrototypeOf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9521978/