gpt4 book ai didi

javascript - 向原型(prototype)添加 getter/setter

转载 作者:行者123 更新时间:2023-11-30 12:08:52 25 4
gpt4 key购买 nike

在下面的代码中,我尝试向原型(prototype)添加 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.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

谢谢。

最佳答案

我认为你必须为内部属性使用不同的名称(它在我的测试中有效),也许使用 _color

Object.defineProperty(p, "color", {
get: function() {return this._color},
set: function(c) {this._color = c}
});

关于javascript - 向原型(prototype)添加 getter/setter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34412879/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com