下面
// 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/
感谢。
答案 0 :(得分: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);
答案 1 :(得分:0)
感谢您的澄清。另一点:因为Object.prototype增加了两个额外的属性(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'; }
子进程从Object.prototype继承awesomeProp和anotherProp,如警报所示。