javascript - 没有常量引用 "this"的 JS 类用于成员访问

标签 javascript class oop 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;

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

换句话说:有什么方法可以使未指定的范围不指向 window,而是指向 this 的当前本地值?

附言我猜这是语言限制,但我还是想再检查一次。

最佳答案

In several other languages e.g. C# & Java, this may be safely omitted when member functions are working with member data in the same class / instance. (I realise that JS is structured fundamentally differently due to it being designed as a prototypal rather than a hierarchical inheritance language.)

不是关于继承链,在js中也是静态的。它是关于 JS 是一种动态语言,全局范围可以随意添加新变量,并且可以使用任意属性修改对象。

因此,让标识符动态解析为局部变量或对象属性是不可能的,我们希望每次都通过使用属性访问器来明确区分它们。

Is there any way to make the unspecified scope NOT point to window, but rather to the current, local value of this?

“未指定范围”是本地范围,是静态确定和优化的。要使其指向一个对象(如果未找到该属性,则返回到变量),您可以使用 with statement .然而,由于这种歧义,它不仅速度慢,而且被认为是不好的做法——(变量的)查找可能会受到非本地代码(与实例交互)的影响,这会破坏封装并且是一个可维护性问题。

My typical JS class structure …

当然,您也可以更改它,并使用通过闭包访问的局部变量作为成员(另请参见 Javascript: Do I need to put this.var for every variable in an object?)。这解决了 this 的问题,但也是 a bit slower (虽然可能仍然比 with 快)。

关于javascript - 没有常量引用 "this"的 JS 类用于成员访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24982471/

相关文章:

javascript - 如何使用流解析缓冲区中的行?

c++ - 尝试退出循环时 Ctrl+Z 不起作用

python - 在 Python 中复制对象实例

Javascript - 反射(reflect)封装的成员

java - Python 多态 VS JAVA 多态

javascript - JQuery - 点击/链接处理程序出现问题

javascript - 什么是 "Enterprise JavaScript"?

javascript - onClick 不渲染不同的 react 组件

java - 如何保护类,使其在包外不可见

css - 如何在自定义 css 框 wordpress 中隐藏主题功能