假设我们已经存在具有此对象的代码:
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并设置为对象属性以便原始代码仍可用?
//#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
//###
答案 0 :(得分: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);