JS类没有经常引用"this"进行成员访问

Eng*_*eer 5 javascript oop class this

我典型的JS类结构如下所示:

MyClass = function(args)
{
   this.myProp1 = undefined;
   this.myProp2 = args[0];
   //...more member data 

   this.foo = function()
   {
       return this.myProp1 + this.myProp2; //<- the problem.
   }
   //...more member functions
}

//if MyClass extends a superclass, add the following...
MyClass.prototype = Object.create(MySuperClass.prototype);
MyClass.prototype.constructor = MyClass;
Run Code Online (Sandbox Code Playgroud)

...我对JS的持续烦恼是我似乎必须this在成员函数中不断使用才能访问这些函数所属的同一对象的属性.在this成员函数处理同一类/实例中的成员数据时,可以安全地省略其他几种语言,例如C#和Java .(我意识到JS的结构根本不同,因为它被设计为原型而不是分层继承语言.)

用另一种方式提出问题:有没有办法让未指明的范围不指向window,而是指当前的本地值this

PS我猜这是一种语言限制,但我想我还是要再检查一下.

Eng*_*eer -1

在这里为后代添加我自己的答案,因为在某个阶段,如果我陷入被迫(1)前置this和(2)使用可怕的之间with,那么有一个(3)rd解决方案可能会很有用。

假设我们不直接访问任何成员数据;相反,我们为每个数据属性提供 getter 和 setter 方法。

在这种情况下,可以使用 Doug Crockford 讨论的私有概念:

MyClass = function()
{
   var prop = undefined;
   this.getProp() {return prop;}
   this.setProp(value) {prop = value;}

   //now in standard, non-getter and -setter methods, we can do...
   this.foo = function()
   {
       return prop + prop; //<- no problem: no more 'this'
   }
}
Run Code Online (Sandbox Code Playgroud)

第(4)种解决方案,安全性较低,但也不那么冗长:

MyClass = function()
{
   var prop = this.prop = undefined; //this.prop for read only! (unsafe)
   this.setProp(value) {prop = this.prop = value;}

   //now in standard, non-getter and -setter methods, we can do...
   this.foo = function()
   {
       return prop + prop; //<- no problem: no more 'this'
   }
}
Run Code Online (Sandbox Code Playgroud)

在(4)中,我们只需要setter,大大减少了冗长。

对于包含大量逻辑的少数方法来说,这种方法效果很好。对于许多较小的方法,其庞大的规模(所有这些访问器方法)最终超过了避免this每次访问本地成员所带来的好处。尽管如此——它确实导致了更清晰的函数内逻辑。