我知道这是一个迟到的回复,但看起来没有人跟进您的回复:
我们知道类实际上是原型的简写,在构造函数中
方法,我们可以实例化对象。但是,我想要的是
在类定义内但在其原型中定义一个道具
构造方法
您可以像以前一样继续声明该类:
class Circle {
constructor (radius) {
this._radius = radius;
}
}
然后像这样定义属性:
Object.defineProperties(obj, {
radius: {
get: function () {
return this._radius;
},
set: function (n) {
this._radius = n;
}
},
area: {
get: function () {
return Math.PI * this._radius * this._radius;
},
set: function (n) {
this._radius = Math.sqrt(n / Math.PI);
}
}
});
或任何你想要的 getter 和 setter。
我给了 实际 _radius 成员一个前导下划线,以将其区分为与添加的 radius 属性分开的成员变量,因为它们都是 this.radius 否则,领先如果您尝试设置它,则会导致堆栈溢出。
但是你问过关于将道具定义放在一个单独的函数中,我的第一个想法是如何使用 Circle 的多个单独实例来做到这一点...
所以这是一个完整的工作示例,其中包含两个 Circle 定义,从一个单独的函数中添加道具,以及它的 CodePen:
https://codepen.io/appurist/pen/ZEbOdeB?editors=0011
class Circle {
constructor(r) {
this._radius = r;
addProps(this);
}
}
function addProps(obj) {
Object.defineProperties(obj, {
radius: {
get: function () {
return this._radius;
},
set: function (n) {
this._radius = n;
}
},
area: {
get: function () {
return Math.PI * this._radius * this._radius;
},
set: function (n) {
this._radius = Math.sqrt(n / Math.PI);
}
}
});
}
let circle = new Circle(7);
let circle2 = new Circle(2);
console.log(`circle radius and area are: ${circle.radius} ${circle.area}`);
circle.radius = 4;
console.log(`circle radius and area now: ${circle.radius} ${circle.area}`);
circle.area = 78.53981633974483;
console.log(`circle radius and area now: ${circle.radius} ${circle.area}`);
console.log(`circle2 radius and area are: ${circle2.radius} ${circle2.area}`);
circle2.radius = 3;
console.log(`circle2 radius and area now: ${circle2.radius} ${circle2.area}`);
circle2.area = 50.26548245743669;
console.log(`circle2 radius and area now: ${circle2.radius} ${circle2.area}`);
上面的输出是:
circle radius and area are: 7 153.93804002589985
circle radius and area now: 4 50.26548245743669
circle radius and area now: 5 78.53981633974483
circle2 radius and area are: 2 12.566370614359172
circle2 radius and area now: 3 28.274333882308138
circle2 radius and area now: 4 50.26548245743669