Object.defineProperty(Object.prototype, 'foo', {value: function() {console.log(foo);}});
(这样添加的属性是不可修改不可枚举不可再次配置的)
当你非要给原生类原型添加方法时,不用 defineProperty 就会给其它程序(如 for in)添加麻烦
当然 getter/setter 要兼容性的话也得要,不然
var obj = {
_name: null,
get name() {
return this._name;
}
set name(val) {
this._name = val;
}
};
会在不支持的浏览器报语法错(没救了,除非 eval)
此时的使用方法:
Object.defineProperty(obj, 'name', {get: function() {return this._name;}, set: function(val) {this._name = val;}});