javascript - 在对象上设置属性时调用函数

标签 javascript node.js

我真的不知道该如何解释,但我会向您展示代码并告诉您我想要实现的目标。

假设我制作了一个快速对象:

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/

相关文章:

javascript - 使用 promise 实现超时 - 抛出错误

javascript - Angularjs 与 Packery.js

javascript - 在实时聊天中实现链接

javascript - 同时具有正零和负零(+0,也写为0和-0)的目的是什么?

javascript - PaymentRequest API 未定义

node.js - 每 5 秒刷新一次 - 如何缓存 s3 文件?

node.js - Mongo 查询没有给出聚合函数的准确结果

javascript - 手动修复 NPM 中的漏洞

javascript - 未捕获的异常错误 "Illegal operation on WrappedNative prototype object"

javascript - 我怎样才能解决这个JavaScript数学问题?