给内置对象或自定义对象添加存取器属性(getter setter)的方法总结

时间:2022-03-02 13:34:53
funct = {   get: function() {    return this._x   },   set: function(value) {    this._x = value   }  }

function Obj(){ this._x=0;}
var obj1=new Obj;
//Obj.prototype = { get x() { return this._x; }, set x(value) { this._x = value; }} //ok //Obj.prototype.__defineGetter__('x', funct['get']); //ok
//Obj.prototype.__defineSetter__('x', funct['set']); Object.defineProperty(obj1, "x", { get: funct['get'], set: funct['set']}); //----- test -------
alert(obj1.x); //
obj1.x = 100;
alert(obj1.x); //
//---- test end -----

~~~ Object.defineProperty() 给对象添加属性

Object.defineProperty(obj, "newDataProperty", {
    value: 101,
    writable: true,
    enumerable: true,
    configurable: true
});

通常我们添加属性只要 obj.attr=value 即可,Object.defineProperty()方法提供更多配置选项,可指定属性是否只读,是否可枚举 可配置