1

ここ

// 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);

Object.defineProperty() の使用は期待どおりに機能しますが、使用すると機能しません

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

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

ありがとう。

4

2 に答える 2

0

明確にしていただきありがとうございます。もう 1 つのポイント: Object.prototype は 2 つの追加のプロパティ (awesomeProp と anotherProp) で拡張されるため、オブジェクトのインスタンスもこれらのプロパティを継承します。

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 は、アラートで示されるように Object.prototype から awesomeProp と anotherProp を継承します。

于 2016-07-30T07:18:58.750 に答える
0

Object.defineProperty()を使用する場合、プロパティにアクセスするときに使用されるアクセサ記述子を提供しますが、コメント付きのコードでは、たまたまメソッドに必要なプロパティにオブジェクトを割り当てるだけです。

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);
于 2016-07-30T04:22:26.407 に答える