admin管理员组文章数量:1421263
So I have learned that in Javascript we can use defineProperties to define multiple properties of object. I have therefore tried it in a simple code below but I am not quiet getting the result I wanted. It seems that the accessors is not working and I don't know why.
var book = {};
Object.defineProperties(book,{
_year: {
value: 2004 },
edition: {
value: 1},
year: {
get: function(){
this._year;},
set: function(value){
if(value>2004){
this._year = value;
this.edition = this.edition + value - 2004;
});
this.year = 2016;
alert(book.edition); //1 why??
So I have learned that in Javascript we can use defineProperties to define multiple properties of object. I have therefore tried it in a simple code below but I am not quiet getting the result I wanted. It seems that the accessors is not working and I don't know why.
var book = {};
Object.defineProperties(book,{
_year: {
value: 2004 },
edition: {
value: 1},
year: {
get: function(){
this._year;},
set: function(value){
if(value>2004){
this._year = value;
this.edition = this.edition + value - 2004;
});
this.year = 2016;
alert(book.edition); //1 why??
Share
Improve this question
edited Oct 11, 2016 at 16:15
Celaro
asked Oct 11, 2016 at 6:54
CelaroCelaro
2262 gold badges8 silver badges20 bronze badges
2
-
You seem to be missing several
}
– j08691 Commented Oct 11, 2016 at 16:22 - Yes, I just realized I was missing those closing brackets, the formatting style did not make it clear. Thanks – Celaro Commented Oct 11, 2016 at 16:27
1 Answer
Reset to default 5You have multiple errors In your code, but the main problem is that, if you define a property with value
then it is by default readonly:
MDN: Object.defineProperty
writable
true if and only if the value associated with the property may be changed with an assignment operator.
Defaults to false.
You need to add writable: true
to make those properties writable.
So your code has to look like this (including the correction for all other errors you had):
var book = {};
Object.defineProperties(book, {
_year: {
value: 2004,
writable: true // << writable
},
edition: {
value: 1,
writable: true // << writable
},
year: {
get: function() {
// << missing return
return this._year;
},
set: function(value) {
if (value > 2004) {
this._year = value;
this.edition = this.edition + value - 2004;
}
}
}
});
book.year = 2016; // << here you used this instead of book
console.log(book.edition);
本文标签: JavaScript Object defineProperties not workingStack Overflow
版权声明:本文标题:JavaScript Object defineProperties not working - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745327149a2653644.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论