我是JS的新手,我写了下面的代码,但我得到了错误"Prototype is not defined“。
var proto = {
describe: function () {
return 'name: ' + this.name;
}
};
var obj = {
[[Prototype]]: proto, //error in this line
name:'obj'
};
console.log(proto.describe());
console.log(obj.describe());发布于 2016-09-06 20:57:38
[[Prototype]]只是对内部属性(原型链中的链接)的规范演讲。要通过原型链将obj链接到proto,可以使用Object.create
var obj = Object.create(proto);
obj.name = 'obj';或ES6/ES2015中的Object.setPrototypeOf:
var obj = {
name:'obj'
};
Object.setPrototypeOf(obj, proto);或者,还有遗留属性__proto__,但不一定推荐使用该属性:
var obj = {
__proto__: proto,
name:'obj'
};发布于 2016-09-06 20:58:58
你不能像这样为对象设置原型。
解决方案是作为其他答案。阅读这篇文章以获得完整的解释:
https://zeekat.nl/articles/constructors-considered-mildly-confusing.html
https://stackoverflow.com/questions/39349478
复制相似问题