最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

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

IT培训 admin 11浏览 0评论

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

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

假设我是一个快速对象:

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.

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

编辑:我也希望能够对属性get做同样的事情(例如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

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

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

假设我是一个快速对象:

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.

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

编辑:我也希望能够对属性get做同样的事情(例如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

发布评论

评论列表 (0)

  1. 暂无评论