开发者

Define setter for hash member in JavaScript

开发者 https://www.devze.com 2023-01-23 09:04 出处:网络
I have hash defined like this: var props = { id: null, title: null, status: null }; I\'d like to define setter for status field (and only for it) doing it as following:

I have hash defined like this:

var props = {
    id: null,
    title: null,
    status: null
};

I'd like to define setter for status field (and only for it) doing it as following:

props.__defineSetter__("status", function(val){
    //Checking correctness of val...
    status = val;
});

But it doesn't work :( So, what's the right way to do 开发者_JS百科it?


Simple, you need to use

this.status = val;

Otherwise you are just setting an unrelated global variable status equal to val.

And as already noted, setters/getters are not implemented in IE.

Also, I'm not sure about how wise it is to have a setter that is the same name as the property it sets. Not sure if this will result in a conflict, but it does seem like a bad idea yes? Ideally the variable that would be set should be hidden in a closure

var props = {
  id: null,
  title: null
};

(function() {

  var status;
  props.__defineSetter__("status", function(val){
    //Checking correctness of val...
    status = val;
  });

  props.__defineGetter__('status', function() { return status; });

}());

This way, status is fully protected from direct access, which is the point of using setters and getters.


The first thing is what MooGoo has pointed out. But also, you can not assign a property setter to an object using the same name as an existing variable in the object.

So your code would have to be something arround this:

var props = {
    id: null,
    title: null,
    hStatus: null,
};

props.__defineSetter__("status", function(v){
    this.hStatus = v;
});

props.__defineGetter__("status", function(){
    return this.hStatus;
});

[edit] Yeah, MooGoo eddited his answer faster then time time I took to write this 8(.


This should work:

props.__setStatus__ = function(val) {
    // Check correctness of val
    this.status = val;
}

Usage:

props.__setStatus__('Alive');
0

上一篇:

:下一篇

精彩评论

暂无评论...
验证码 换一张
取 消