このオブジェクトを持つ既存のコードがあるとします。
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
元のコードが引き続き機能するように、カスタムの get および set をオブジェクト プロパティに追加する方法はありますか?
//#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
//###