[英]How to set the prototype of a constructor function?
let shape = { type: 10, getTyp() { return "triangle"; } }; function Triangle() {} Object.setPrototypeOf(Triangle, shape); let t = new Triangle(); console.dir(t.type); //undefined
为什么Triangle的原型没有变化? t.type === undefined
但不是 10;
您将Constructor.prototype
与instance
的内部[[Prototype]]
混淆了, Object.setPrototypeOf()
设置了什么。
在这种情况下,您应该使用前者:
let shape = { type: 10, getTyp() { return "triangle"; } }; function Triangle() {} Triangle.prototype=shape; let t = new Triangle(); console.dir(t.type); //10
上述工作,但是,为了确保 class constructor
指向正确的 function,不要覆盖Constructor.prototype
。 相反,为它分配属性:
let shape = { type: 10, getTyp() { return "triangle"; } }; function Triangle() {} Object.assign(Triangle.prototype,shape); let t = new Triangle(); console.dir(t.type); //10
原因Triangle
的实例继承自Triangle.prototype
。 你想改变它:
Object.setPrototypeOf(Triangle.prototype,/*...*/);
如果设置了Triangle
的原型,则可以直接在Triangle
上访问该属性:
Triangle.shape
这基本上就是如何继承 static 属性
代替
Object.setPrototypeOf(Triangle, shape)
你需要做的就是
Triangle.prototype = shape
Object.getPrototypeOf(Triangle)
指的是Triangle[[Prototype]]
(或非标准Triangle.__proto__
属性),而不是您似乎预期的Triangle.prototype
。
根据文档, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/setPrototypeOf ,这个 function 的第一个参数应该是一个 ZA626CFDE63131BDCBBB68CFDE6913145B 你给它传递了一个 class。
这不是您想要的,但它是如何正确使用 function 的示例:
let shape = {
type: 10,
getTyp() {
return "triangle";
}
};
const Triangle = {};
Object.setPrototypeOf(Triangle, shape);
let t = Triangle;
console.dir(t.type);
[编辑]
这是另一个概念:
let shape = {
type: 10,
getTyp() {
return "triangle";
}
};
function Triangle() {
Object.setPrototypeOf(this, shape);
}
let t = new Triangle();
console.dir(t.type); //undefined
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.