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);
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745327149a4622710.html
评论列表(0条)