假设我们有一个已经存在的具有此对象的代码:
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
//###