在对象上设置属性时调用函数 [英] Call a function when a property gets set on an object

查看:98
本文介绍了在对象上设置属性时调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的不知道怎么解释这个,但我会告诉你代码并告诉你我想要实现的目标。

I don't really know how to explain this but I'll show you code and tell you what I'd like to achieve.

假设我说快速对象:

var test = {};

然后我为它设置了一个属性:(我坚持语法,它不能使用任何函数作为setter)

And then I set a property to it: (I insist on the syntax, it mustn't use any function as the setter)

test.hello = 'world';

非常简单,是吗?现在我想向该对象添加一个函数,每次设置一个新属性时都会调用该函数。像这样:

Pretty simple, eh? Now I'd like to add a function to that object that would get called everytime a new property gets set. Like this:

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.

我不知道是否可能,但这将是非常惊人的。任何人都知道如何实现这一目标?

I don't know if it's possible, but that would be quite amazing. Anyone has an idea of how to achieve so?

编辑:我也希望能够为财产获取做同样的事情(所以 test.hello 会调用 get('hello')例如。)

I'd like also to be able to do the same for property get (so test.hello would call get('hello') for example).

EDIT2:这是针对使用node.js的服务器端javascript

非常感谢,祝你有愉快的一天!

Thanks a lot and have a nice day!

推荐答案

在chrome中尝试此示例(如之前的评论所述,它使用 ES6代理):

try this example in chrome (as mentioned in previous comments it uses ES6 Proxy):

var p = Proxy.create({
  get: function(proxy, name) {
    console.log('read request to ' + name + ' property');
    if (name=="test_test")
       return 1234;
    else
       return "Meh";
  },
  set: function(proxy, 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

这篇关于在对象上设置属性时调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆