简体   繁体   中英

how do I use get operator on variable after creating object?

I recently asked a question here where I found I could use {get a() {return 'whatev'}} to control what happens when variables are get and set.

I want to know if/how I can do that after a variable is created, something like this, except that this doesn't work:

abc=new Object();
abc._a = NaN;
abc.get a() {
return abc._a;
}
abc.set a(i) {
abc._a=i;
}

In the other question it showed me only how to do it when making a new object:

abc = {
  _a:NaN;
  get a() {
    return _a;    
    }
  set a(i) {
    _a=i;
    }
  }

EDIT: I found ' defineGetter ' and ' defineSetter ' on https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/defineGetter , it works, but it says it is non-standard. Is there a more standard way?

The get and set are part of the Object Initializer. They are not properties of the object, and as such, can not be added later.

See ECMAScript 1.5, Section 11.1.5 Object Initializer for more info.

Only ES5 (ECMAScript Edition 5) will support getters and setters. Unfortunately, ES5 isn't fully implemented by any browser just yet, only partially.

Current Javascript implementations do not support getters and setters, not in a standard or cross-browser way. You'll have to write explicit getA and setA functions, sorry.

Here's the recommended way in ES3 (which works across all modern browsers, even in IE6), using closures:

var abc = (function () {
  var a = NaN;
  return {
    getA: function () {
        return a;
    },
    setA: function (value) {
        a = value;
    }
  };
})();

This will give you an object in the variable abc , with two functions: getA() and setA(value) . The only way to get at a is thru those two methods.

abc.getA()
// NaN

abc.setA(25);
abc.getA();
// 25

The a variable itself is hidden from the outside world, because it's only present within the scope of the anonymous function used to create the object.

The non-standard __defineGetter__ and __defineSetter__ are supported in most browsers (Mozilla, WebKit and Opera but not IE). They will do what you want and are the best-supported option (short of replacing your property with explicit getX() and setX() methods). Example:

var o = {};
o._a = "foo";

o.__defineGetter__("a", function() {
    return this._a;
});

o.__defineSetter__("a", function(val) {
    return this._a = val;
});

alert(o.a);  // "foo"
o.a = "bar";
alert(o._a); // "bar

Update :

Note, the correct way to do this now, is to use Object.defineProperty or Object.defineProperties.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM