Javascript 向原型添加getter/setter
在下面的代码中,我尝试将getter和setter添加到原型中Javascript 向原型添加getter/setter,javascript,Javascript,在下面的代码中,我尝试将getter和setter添加到原型中 function Car(make, model, year) { this.make = make; this.model = model; this.year = year; this.displayCar = displayCar; } function displayCar() { console.log("A Beautiful " + this.year + " " + this
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
this.displayCar = displayCar;
}
function displayCar() {
console.log("A Beautiful " + this.year + " " + this.color + " " + this.make + " " + this.model);
}
var c1 = new Car("Ford", "Mustang", 1969);
var c2 = new Car("Skoda", "Octavia", 1999);
var p = Car.prototype;
Object.defineProperty(p, "color", {
get: function() {return this.color},
set: function(c) {this.color = c}
});
c2.color = "White";
c2.displayCar();
有人能帮我理解为什么我在第18行出现这个错误吗:
Uncaught RangeError: Maximum call stack size exceeded
谢谢。我认为您必须为内部属性使用不同的名称(它在我的测试中起作用),或者使用\u颜色
Object.defineProperty(p, "color", {
get: function() {return this._color},
set: function(c) {this._color = c}
});
问题在于这些方面:
var p = Car.prototype;
Object.defineProperty(p, "color", {
set: function(c) {this.color = c} // Setter
});
c2.color = "White";
说明:
这里的情况是,您正在将c2.color设置为“白色”。这个触发器是您以前定义的setter。此setter将This.color再次设置为“白色”,这将再次调用setter。等等直到超过堆栈大小
因此,您陷入了一个无限递归问题中
如何解决它
此问题的一个可能解决方案是将“color”属性的值存储在另一个属性中,如下所示:
var p = Car.prototype;
Object.defineProperty(p, "color", {
get: function() {return this.color2},
set: function(c) {this.color2 = c}
});
c2.color = "White";
c2.color // White!
希望能有帮助!!;) 我喜欢变量名前的下划线。