Javascript - 在类的函数成员中正确使用“this”

Javascript - Correct use of 'this' in a function member of a class

本文关键字:this 成员 函数 Javascript      更新时间:2023-09-26

我想在类的函数成员中使用this对象。该函数可能因类的实例而异。它工作正常,但谷歌闭包编译器向我发送警告,让我觉得我没有正确做。

因此,我的问题:在既不是原型也不是构造函数的函数中使用this的正确方法是什么?如果没有,我该怎么办而不是尝试在那里使用this

以下是我正在尝试做的事情的说明:

/** @constructor */
function MyAlert() {}
/** @type {string} */
MyAlert.prototype.name = "joe";
/** @type {function()} */
MyAlert.prototype.myAlert;
/** @type {MyAlert} */
var formalAlert = new MyAlert();
/** @type {MyAlert} */
var informalAlert = new MyAlert();
informalAlert.myAlert = function() {alert("Hi " + this.name);}
formalAlert.myAlert = function() {alert("Good morning Mr " + this.name);}
formalAlert.myAlert();
informalAlert.myAlert();

编译时,我收到此警告,但找不到解决方法:

JSC_USED_GLOBAL_THIS: dangerous use of the global this object at line 11 character 57
formalAlert.myAlert = function() {alert("Good morning" + this.name);}
                                                         ^

非常感谢您的帮助!

从您的示例中:

formalAlert.myAlert = function() {...}

在 formAlert 上创建一个新的静态属性,该属性隐藏(而不是替换)原型。虽然仍然完全有效的javascript,但重要的是要认识到编译器正确地将这些属性视为不同的属性。

要消除此警告,您只需告诉编译器"this"对象的类型:

formalAlert.myAlert = /** @this {MyAlert} */ function() {...};