每当在 Javascript 对象上设置新属性时,我如何获得回调?
即我不知道要设置哪些属性,但想要对设置的任何属性进行回调。
我想要的是
var obj = {};
obj.a = "something"; // triggers callback function
function callback(obj,key,val) {
console.log(key + " was set to " + val + " on ", obj);
}
这可能吗?
每当在 Javascript 对象上设置新属性时,我如何获得回调?
即我不知道要设置哪些属性,但想要对设置的任何属性进行回调。
我想要的是
var obj = {};
obj.a = "something"; // triggers callback function
function callback(obj,key,val) {
console.log(key + " was set to " + val + " on ", obj);
}
这可能吗?
不幸的是,JavaScript 不会让您知道属性何时更改。很多时候我希望它会,但因为它不会,我不得不找到一个解决方法。不是直接设置属性,而是通过触发回调函数的 setter 方法设置它(也可能使用 getter 方法来访问属性),如下所示:
function callback(obj,key,val) {
console.log(key + " was set to " + val + " on ", obj);
}
var obj = {};
obj.setA=function(value){
obj.a=value;
callback(obj,'a',value);// triggers callback function
}
obj.getA=function(){
return obj.a;
}
obj.setA("something");
jsFiddle:http: //jsfiddle.net/jdwire/v8sJt/
编辑:如果您想完全防止在没有回调的情况下更改属性,则另一种选择:
function callback(obj,key,val) {
console.log(key + " was set to " + val + " on ", obj);
}
var obj={};
(function(){
var a=null;
obj.setA=function(value){
a=value;
callback(obj,'a',value);// triggers callback function
}
obj.getA=function(){
return a;
}
})()
console.log("a is "+obj.getA());// a is null
obj.setA("something"); // Set a to something
console.log("a is now "+obj.getA()); // a is now something
obj.a="something else"; // Set obj.a to something else to show how a is only accessible through setA
console.log("a is still "+obj.getA()); // a is still something
jsFiddle:http: //jsfiddle.net/jdwire/wwaL2/
最好的办法是一个 setter 函数,你不需要一个 getter,
var obj = {};
setKey(obj, 'a', "something"); // triggers callback function
function setKey(obj, key, val){
obj[key] = val;
callback(obj, key, val);
}
function callback(obj, key, val) {
console.log(key + " was set to " + val + " on ", obj);
}
尽可能通用,不要对所有键执行不同的功能
在这里试试
最好的办法是拥有 setter 和 getter 方法。但是根据您之前的实现,您仍然可以在不使用 setter 和 getter 的情况下更改您的对象属性。因此,您应该将敏感变量设为私有。这是一个简短的例子:
var Person = (function() {
function Person() {};
var _name;
Person.prototype.setName = function(name) {
_name = name;
};
Person.prototype.getName = function() {
return _name;
};
return Person;
})();
var john = new Person();
john.getName();
// => undefined
john.setName("John");
john.getName();
// => "John"
john._name;
// => undefined
john._name = "NOT John";
john.getName();
// => "John"