Getters and setters in javascript

I start with javascript and especially with the OOP template.

My question is simple. In the setter, is there a way to keep the same name for a parameter and a variable of a private class? I looked everywhere, but could not find anyone mentioning this, just examples with different variable names. I am very picky about my code, and I need to give it two different names.

Taking an example from http://ejohn.org/blog/javascript-getters-and-setters/

function Field(val){
    this.value = val;
}
Field.prototype = {
    get value(){
        return this._value;
    },
    set value(val){
        this._value = val;
    }
};

you can see the val parameter in the tuner, but the property is actually a value. Since this is javascript, I cannot just make this.value = value, because "this" will make it public. Value = value will be treated as a parameter (and will be very strange). Is there really no way to do this? If not, is there a “best practice” for this situation? I think the underline may be true, but I'm just picky, so I just want to make sure there is no other way.

Thank!

+5
source share
2 answers

You can use closure to hide the variable.

function MyClass {
  var value;

  this.getValue = function() {
    return value;
  }

  this.setValue = function(val) {
    value = val;
  }

}

MyClass value , (). , value . getValue() setValue() MyClass, value.

+5

:

(function(exports){

    exports.field = {};
    var _value = '123';

    exports.field.get = function(){
        return _value;
    }

    exports.field.set = function(val){
        _value = val;
    }

})(window);

console.log(field.get());

JS.

+1

All Articles