admin管理员组文章数量:1356424
I want to convert a data property to accessor property using Object.defineProperty() . Consider the code for this which leads to Uncaught RangeError: Maximum call stack size exceeded
error
var c = { name: 'abcde'};
Object.defineProperty(c, 'name', {
get: function() {
return this.name; //causes stack overflow
},
set: function(x) {
this.name = x; //causes stack overflow
}
});
c.name="xyz";
console.log(c.name);
I understood why the error crops in. One of the proposed solution is to remove 'this' from getter and setter and it seems to work.
var c = { name: 'abcde'};
Object.defineProperty(c, 'name', {
get: function() {
return name; //removed this
},
set: function(x) {
name = x; //removed this
}
});
c.name="xyz";
console.log(c.name);
What is happening ? In general , I want to ask how to convert a data property to accessor property using Object.defineProperty() ?
I want to convert a data property to accessor property using Object.defineProperty() . Consider the code for this which leads to Uncaught RangeError: Maximum call stack size exceeded
error
var c = { name: 'abcde'};
Object.defineProperty(c, 'name', {
get: function() {
return this.name; //causes stack overflow
},
set: function(x) {
this.name = x; //causes stack overflow
}
});
c.name="xyz";
console.log(c.name);
I understood why the error crops in. One of the proposed solution is to remove 'this' from getter and setter and it seems to work.
var c = { name: 'abcde'};
Object.defineProperty(c, 'name', {
get: function() {
return name; //removed this
},
set: function(x) {
name = x; //removed this
}
});
c.name="xyz";
console.log(c.name);
What is happening ? In general , I want to ask how to convert a data property to accessor property using Object.defineProperty() ?
Share Improve this question edited Jan 23, 2017 at 18:57 Number945 asked Jan 23, 2017 at 10:11 Number945Number945 4,98010 gold badges53 silver badges90 bronze badges1 Answer
Reset to default 7The second code doesn't actually work because it uses the global variable called name
to store the value, instead of storing it in the object c
.
It would be rejected by ES5 "strict mode", if it weren't for the fact that window.name
is a default property of the global object in browsers.
A more appropriate fix would be to store the value in a lexically scoped private variable:
var c = (function() {
var obj = {};
var name = "abcde";
Object.defineProperty(obj, "name", {
get: function() {
return name;
},
set: function(x) {
name = x;
}
});
return obj;
})();
本文标签: javascriptUsing getter and setter with ObjectdefinePropertyStack Overflow
版权声明:本文标题:javascript - Using getter and setter with Object.defineProperty - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743975334a2570855.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论