I first found this idea on this site:

http://theburningmonk.com/2011/01/javascript-dynamically-generating-accessor-and-mutation-methods/

The point is to assign a local variable to the class scope to set dynamic class properties.

In this code I set a local variable _this equal to the class scope. But for some reason, the properties of _this are accessible outside of the class. Why is this? _this is declared a private member when it is created.

var MyClass = function( arg )
{
var _this = this;
_this.arg = arg;

// Creates accessor/mutator methods for each private field assigned to _this.
for (var prop in _this)
{
    // Camelcases methods.
    var camel = prop.charAt(0).toUpperCase() + prop.slice(1);

    // Accessor
    _this["get" + camel] = function() {return _this[prop];};

    // Mutator
    _this["set" + camel] = function ( newValue ) {_this[prop] = newValue;};
}
};

var obj = new MyClass("value");
alert(obj.getArg());

How come this will run? It will alert "value". This shouldn't be accessible because _this is declared privately. When I wrote this, I did the mutator/accessor assignment wrong; or so I though.

I meant to write this, assigning these methods to the class scope:

    // Accessor
    this["get" + camel] = function() {return _this[prop];};

    // Mutator
    this["set" + camel] = function ( newValue ) {_this[prop] = newValue;};

But either work. Why is it that _this' private methods are available?

Any help would be awesome!

Thanks, Confused Scripter

有帮助吗?

解决方案

The value of _this is just a copy of this, so both will refer to the newly-created object. It's the object itself that's available.

In other words, one reference to an object is as good as another. In your code, there are three:

  1. this, inside the constructor
  2. _this, also inside the constructor
  3. obj, which is assigned a reference to the same object as a result of the new expression.

In newer JavaScript implementations, it's possible to make properties be hidden, but that hiding applies globally. JavaScript doesn't have anything like "class scope" that languages like C++ or Java do.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top