Multiple Object Properties JavaScript -
got code snippet in javascript defines multiple properties object.
var book = {}; object.defineproperties(book , { _year: { value: 2004 }, edition: { value: 1 }, year: { get: function() { return this._year; }, set: function(newvalue) { if (newvalue > 2004) { this._year = newvalue; this.edition += newvalue - 2004; } } } }); book.year = 2005; alert(book.edition);
so book has code claims alert(book.edition);
would display 2
.instead , displays 1
. seems never executes part of accessors property code (year: get: set:)
. knows why happening?
edition
has been defined non-writable property -- writable
descriptor property hasn't been specified , false
default. hence this.edition += ...
fails silently. same applies _year
property well.
_year: { writable: true, value: 2004 }, edition: { writable: true, value: 1 },
note: assigning non-writable property throws error in strict mode, can add 'use strict';
pragma spot these errors more easily.
reference:
- mdn -
object.defineproperties()
- mdn -
object.defineproperty()
-- explains descriptors more in-depth.
Comments
Post a Comment