将get/set函数附加到js中的objects属性

ben*_*ben 10 javascript oop binding

我基本上有一个对象:

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

let a = new foo();
a.setting = true; // a.refresh() is triggered
Run Code Online (Sandbox Code Playgroud)

我需要随时.setting写入触发刷新.我觉得它与它有关bind,但我无法理解它.

Ada*_*dam 13

您可以使用JavaScript getter和setter.请参阅有关该主题的MDC文档John Resig关于该主题的博客文章.请注意,并非所有浏览器都支持此功

var Foo = function()//constructor
{
   this._settings = false;//hidden variable by convention
   this.__defineGetter__("settings", function(){
     return _settings;//now foo.settings will give you the value in the hidden var
   });

   this.__defineSetter__("settings", function(s){
      _settings = s;//set the hidden var with foo.settings = x
      this.refresh();//trigger refresh when that happens
   });

   this.refresh = function(){
      alert("Refreshed!");//for testing
   }
}

var a = new Foo();//create new object
a.settings = true;//change the property
//a.refresh() is triggered
Run Code Online (Sandbox Code Playgroud)

试试吧!


Boa*_*niv 5

您需要为对象使用getter和setter.一种方法是直接使用getter/setter函数:

var foo = function()
{
   this.setting = false;
   this.getSetting = function() { return this.setting; }
   this.setSetting = function(val) { this.setting = val; this.refresh(); }
   this.refresh = function()
   {...}
}
Run Code Online (Sandbox Code Playgroud)

如果你想透明地使用foo.setting作为属性,那么就有语言结构,但不幸的是它们不能跨浏览器互操作.在3年前的某种程度上,有一种方法可以支持Mozilla,Safari,Chrome和Opera以及另一种Internet Explorer方法.这是标准方法:

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

IE9还有别的东西,我不确定它是否适用于非DOM对象.