附加get / set函数在JS对象属性 [英] attach get/set function to objects property in js

查看:422
本文介绍了附加get / set函数在JS对象属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我基本上是有一个对象:

I essentially have an object:

var foo = function()
{
   this.setting=false;
   this.refresh = function()
   {...}
}

let a = new foo();
a.setting=true;
//a.refresh() is triggered

我需要触发随时刷新 .setting 被写入。我觉得它是与绑定,但我不能完全得到它。

I need to trigger refresh anytime .setting is written to. I feel like it has something to do with bind, but I couldn't quite get it.

推荐答案

您需要使用一个getter和你的对象的制定者。一种方法是使用的getter / setter函数直接:

You need to use a getter and a setter for your object. One way is to use getter/setter functions directly:

var foo = function()
{
   this.setting = false;
   this.getSetting = function() { return this.setting; }
   this.setSetting = function(val) { this.setting = val; this.refresh(); }
   this.refresh = function()
   {...}
}

如果您希望透明地使用foo.setting作为一个属性,也有对语言结构,但遗憾的是他们没有跨浏览器的互操作性。在有些倒退到3年前的,还有由Mozilla,Safari浏览器,Chrome和Opera和Internet Explorer的另一种方法支持的一个方法。这是标准的方法:

If you want to use foo.setting transparently as an attribute, there are language constructs for that, but unfortunately they are not interoperable across browsers. In somewhat of a throwback to 3 years ago, there's one method supported by Mozilla, Safari, Chrome and Opera and another method for Internet Explorer. This is the standard method:

http://robertnyman.com/2009/05/28/getters-and-setters-with-javascript-$c$c-samples-and-demos/

IE9有别的事情,我不知道,如果它甚至适用于非DOM对象。

IE9 has something else, and I'm not sure if it even works for non-DOM objects.

这篇关于附加get / set函数在JS对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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