__defineGetter__ && __defineSetter__

时间:2022-02-20 01:08:56

看别人源码碰到的,做个备忘。

//针对对象增加get\set方法,返回绑定函数的返回值
Date.prototype.__defineGetter__('getYear', function() {return this.getFullYear();});
Date.prototype.__defineSetter__('setYear', function(year) {this.setFullYear(year)});
Date.prototype.__defineGetter__('sayHello', function() {return "Hello"}); var now = new Date;
console.log(now.getYear); //2015
now.setYear = 2011;
console.log(now.getYear); // console.log(now.sayHello);