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

时间:2012-04-27 18:12:39

标签: javascript annotations google-closure-compiler

我想在类的函数成员中使用this对象。根据类的实例,函数可以不同。它工作正常,但Google Closure Compiler向我发出警告,这让我觉得我没有正确地做到这一点。

因此我的问题是:在既不是原型也不是构造函数的函数中使用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();

虽然compiling我收到此警告但无法找到解决方法:

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

非常感谢你的帮助!

1 个答案:

答案 0 :(得分:2)

从你的例子:

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

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

要使此警告静音,您只需告诉编译器'this'对象的类型:

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