2013-04-30 60 views
-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 
//### 

回答

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);