1

Here

// inherit methods of Date to extend it.
var extendDate=Date.prototype;

// add year property to Date.prototype, thus to an instance of Date
/*extendDate.year={
    get: function() { return this.getFullYear(); },
    set: function(y) { this.setFullYear(y); }
};*/

Object.defineProperty(extendDate, "year", {
  get: function() { return this.getFullYear(); },
  set: function(y) { this.setFullYear(y); }
});


// test year's getter and setter
// first, create an instance of Date
// remember, Date now inherits property year
var now=new Date();
alert(now);
now.year=2000;
alert(now);

Using Object.defineProperty() works as expected but not when I use

extendDate.year={
        get: function() { return this.getFullYear(); },
        set: function(y) { this.setFullYear(y); }
};

JSFiddle: https://jsfiddle.net/od53se26/1/

Thanks.

Logan Lee
  • 807
  • 9
  • 21

2 Answers2

0

When using Object.defineProperty(), you are providing accessor descriptors that are used when accessing a property, whereas in the commented code you are simply assigning an object to a property that happens to have to methods.

var obj = Object.prototype;

obj.awesomeProp = {
  get: function() { return 'chicken satay'; }
};
// logs the whole awesomeProp object
console.log(obj.awesomeProp);
// logs "function () { return 'chicken satay'; }"
console.log(obj.awesomeProp.get);

Object.defineProperty(obj, 'anotherProp', {
  get: function() { return 'chicken soup'; }
});
// logs "chicken soup"
console.log(obj.anotherProp);
// logs *undefined*
console.log(obj.anotherProp.get);
Will
  • 2,163
  • 1
  • 22
  • 22
0

Thanks for the clarification. Just another point: since Object.prototype is augmented with two extra properties(awesomeProp and anotherProp), any instance of object also inherits these properties.

Jsfiddle https://jsfiddle.net/1nxtmeyu/

var obj = Object.prototype;

obj.awesomeProp = {
  get: function() { return 'chicken satay'; }
};

Object.defineProperty(obj, 'anotherProp', {
  get: function() { return 'chicken soup'; }
});

var AnyObj=function() {};
// AnyObj inherited awesomeProp and anotherProp
var child=new AnyObj();
alert(child.anotherProp);        // alerts chicken soup
alert(child.awesomeProp.get);        // alerts function() { return 'chicken satay'; }

child inherits awesomeProp and anotherProp from Object.prototype as shown by the alerts.

Logan Lee
  • 807
  • 9
  • 21