gpt4 book ai didi

javascript - 对象文字符号 getter 和 setter : too much recursion

转载 作者:行者123 更新时间:2023-11-30 07:14:29 24 4
gpt4 key购买 nike

我不熟悉使用 js 编写脚本并遵循 MDN 的 JavaScript 指南。我无法轻易理解一些 js 概念。

尝试了以下代码(来自 Java 背景),但浏览器给出了太多的递归错误。

//jshint esnext: true
console.clear();

var student = {
get name() {
return this.name;
},

set name(value) {//Should we not use same name as local variable?
this.name = value;
},

get age() {
return this.age;
},

set age(value) {
this.age = value;
}
};

var mike = Object.create(student);
console.log(mike.age);
console.log(mike.name);

mike.age = 29;
console.log(mike.age);

mike.name = "JS";
console.log(mike.name);

这是怎么回事?

最佳答案

您应该在 getter 和 setter 的上下文中引用私有(private)变量,而不是引用相同的名称。与公共(public)名称相比,常见的模式是在每个局部变量前加上下划线作为前缀。

var student = {
get name() {
return this._name;
},

set name(value) {//Should we not use same name as local variable?
this._name = value;
},

get age() {
return this._age;
},

set age(value) {
this._age = value;
}
};

关于javascript - 对象文字符号 getter 和 setter : too much recursion,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32712485/

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