我真的不知道该如何解释,但我会向您展示代码并告诉您我想要实现的目标。
假设我制作了一个快速对象:
var test = {};
然后我给它设置了一个属性:(我坚持语法,它不能使用任何函数作为setter)
test.hello = 'world';
很简单,嗯?现在我想向该对象添加一个函数,每次设置新属性时都会调用该函数。像这样:
var test = {
newPropertyHasBeenSet: function(name){
console.log(name + 'has been set.');
}
};
test.hello = 'world';
// Now newPropertyHasBeenSet gets called with 'hello' as an argument.
// hello has been set.
我不知道这是否可能,但那将是非常了不起的。任何人都知道如何实现这一点?
编辑:我也希望能够为属性获取做同样的事情(所以 test.hello
会调用 get('hello')
例如) .
EDIT2:这是使用 node.js 的服务器端 javascript。
非常感谢,祝您有愉快的一天!
最佳答案
在 chrome 中试试这个例子(正如之前评论中提到的,它使用 ES6 Proxy ):
var p = new Proxy(
{},
{
get: function(obj, name) {
console.log('read request to ' + name + ' property');
if (name == 'test_test') return 1234;
else return 'Meh';
},
set: function(obj, name, value) {
console.log('write request to ' + name + ' property with ' + value + ' value');
},
}
);
console.log(p.test_test);
console.log(p.test);
p.qqq = 'test';
结果:
read request to test_test property
1234
read request to test property
Meh
write request to qqq property with test value
关于javascript - 在对象上设置属性时调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11552064/