2012-04-27 59 views
2

我想在类的函数成员中使用this对象。该功能可以根据类的实例而有所不同。它工作正常,但Google Closure编译器向我发送警告,这让我觉得我没有做好。Javascript - 在类的函数成员中正确使用'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(); 

虽然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);} 
                 ^

谢谢很多为您的帮助!

+0

为什么你难道不被附加这些方法的原型? – Tejs 2012-04-27 18:15:05

+0

我不担心。你正在做的是覆盖从原型继承的行为的完美有效的方法。 – Prestaul 2012-04-27 18:16:56

+3

[Closure Compiler Warning'危险使用全局this对象吗?]的可能重复(http://stackoverflow.com/questions/5301373/closure-compiler-warning-dangerous-use-of-the-global-this-对象) – 2012-04-27 18:16:57

回答

2

从你的例子:

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

创建于formalAlert一个新的静态属性,它的阴影(不是替代)的原型。虽然仍然是完全有效的JavaScript,但认识到编译器正确地将这些视为不同的属性是很重要的。

要消除此警告,你只需要告诉编译器“这个”对象类型:

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

JSDoc的评论也可以上线。 – John 2012-04-28 15:04:35

相关问题