-1

假设我们有一个已经存在的具有此对象的代码:

function randomObject(id){
this.id = id;
}

将事件添加到例如 id 属性的简单方法如下:

function myObject(_id){
    this._id = _id;
    this.id = function(Id){
        //get
        if(Id === undefined){
          fireGetEvent();
          return this._id;
        }
        //or set
        fireSetEvent();
        this._id = Id;
    }

然而,这有一个大问题。这样就不可能将事件添加到现有对象,因为现在必须以这种方式设置或获取属性:

anObject.id(5); //set
alert(anObject.id()); //get

这将停止工作:

anObject.id = 5; //set
alert(anObject.id); //get

有什么方法可以添加自定义获取和设置到对象属性,以便原始代码仍然可以工作?

//#can't touch this:
function randomObject(id){
this.id = id;
}
//Call this on property change
function callMeMaybe(num){
alert("You're a genius! Here's your lucky number: " + num);
}
var anObject = new randomObject(5);
//#

//##Do whatever you like to solve this puzzle and make setting id on "anObject" call "callMeMaybe"
// Your code here
//##

//###Can't touch this:
anObject.id = 42; //Here "callMeMaybe" should be fired
alert(anObject.id); //Here id should be displayed properly
//###
4

1 回答 1

1

JavaScript 提供了一种内置的方法来添加 getter 和 setter。这可能与您支持的浏览器要求兼容,也可能不兼容。

这是描述兼容性的页面。 http://robertnyman.com/javascript/javascript-getters-setters.html

var o = {
    id: null
};

Object.defineProperty(o, "id", {
    get: function () {
        console.log('getter called');
        return this.idPropValue;
    },
    set: function (value) {
        console.log('setter called with value: ' + value);
        this.idPropValue = value;
    }
});

o.id = 123;
var id = o.id;
alert(id);
于 2013-04-30T17:29:41.223 回答