我真的不知道如何解释这一点,但我会向您展示代码并告诉您我想要实现的目标。
假设我制作了一个快速对象:
var test = {};
然后我为其设置一个属性:(我insist在语法上,它不能使用任何函数作为设置器)
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 代理):
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';
result:
read request to test_test property
1234
read request to test property
Meh
write request to qqq property with test value
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)