-1
比方說,我們有一個具有此對象的現有代碼:的Javascript添加事件,在運行時對象屬性
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
//###