Javascript将类作用域赋给局部变量是无效的

Javascript assigning class scope to local variable ineffective

本文关键字:局部变量 无效 作用域 Javascript      更新时间:2023-09-26

我最初是在这个网站上发现这个想法的:

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

关键是要给类作用域分配一个局部变量,以设置动态的类属性。

在这段代码中,我设置了一个局部变量_this等于类作用域。但是由于某种原因,_this的属性可以在类之外访问。为什么会这样?_this在创建时被声明为私有成员。

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());

为什么这个会运行?它会提示"value"。它不应该是可访问的,因为_this是私有声明的。当我写这个的时候,我做错了赋值;我是这么想的。

我打算这样写,将这些方法分配给类作用域:

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

但是都可以。为什么_this的私有方法是可用的?

任何帮助都太棒了!

谢谢,困惑的脚本

_this的值只是this的副本,因此两者都将引用新创建的对象。对象本身是可用的

换句话说,一个对象的引用和另一个对象的引用一样好。在您的代码中,有三个:

  1. this,内部构造器
  2. _this,也在构造器
  3. obj,作为new表达式的结果,它被分配给同一个对象的引用。

在较新的JavaScript实现中,可以使属性被隐藏,但这种隐藏适用于全局。JavaScript没有像c++或Java那样的"类作用域"。