attach get/set function to objects property in js

2019-02-02 00:39发布

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

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.

6条回答
何必那么认真
2楼-- · 2019-02-02 01:10

I don't why you are trying to use the "new" operator, you will be better using the object literal. Now, if you are looking similar to, let's say, C# properties, you could do something like this:

var myObject = function(){
    //Private Members
    var myProperty = '';

        //Privileged Setter
        this.setMyProperty = function(value){
            myProperty = value;
        };

        //Privileged Getter
        this.getMyProperty = function(){
            return myProperty;
        }

}

var MyNewObject = new myObject();
MyNewObject.setMyProperty("Hello, World!");
MyNewObject.getMyProperty();

For more info, I recommend this: http://www.crockford.com/javascript/private.html

查看更多
倾城 Initia
3楼-- · 2019-02-02 01:11

Are you looking for a setting setter? Something like this?

// renamed settings property with underscore
this._settings = false;

this.settings = function(s) {
     if(s !== undefined) {
        this._settings = s;
        this.refresh();
     }

     return this._settings;
};

...


var f = new foo();
f.setSettings(mySettings);

I tend to combine my getter and setter into one method in JavaScript since it's so easy to do. The downside to this is _settings is still public on your object and anyone can directly write to it. The only way to hide it is to use a closure, which requires a totally different approach to creating your objects.

查看更多
Juvenile、少年°
4楼-- · 2019-02-02 01:14

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()
   {...}
}

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-code-samples-and-demos/

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

查看更多
戒情不戒烟
5楼-- · 2019-02-02 01:15

I know this is an old question that has already been answered, but I'd like to provide a solution that takes advantage of JavaScript's latest syntax.


Define a class with a getter and setter:

class Foo {
  constructor() {
    this._setting = false;
  }

  get setting() {
    return this._setting;
  }

  set setting(value) {
    this._setting = value;
    this.refresh();
  }

  refresh() {
    console.log("refresh!");
  }
}

let foo = new Foo();
foo.setting = true; // foo.refresh() is called
查看更多
神经病院院长
6楼-- · 2019-02-02 01:17

You could use JavaScript getters and setters. See the MDC documentation on the subject and John Resig's blog post on the subject. Note that not all browsers support this.

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

Try it!

查看更多
趁早两清
7楼-- · 2019-02-02 01:21

If you aren't limited with old browsers you may try to use the approach described here

查看更多
登录 后发表回答