我想在类的函数成员中使用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);}
^
谢谢很多为您的帮助!
为什么你难道不被附加这些方法的原型? – Tejs 2012-04-27 18:15:05
我不担心。你正在做的是覆盖从原型继承的行为的完美有效的方法。 – Prestaul 2012-04-27 18:16:56
[Closure Compiler Warning'危险使用全局this对象吗?]的可能重复(http://stackoverflow.com/questions/5301373/closure-compiler-warning-dangerous-use-of-the-global-this-对象) – 2012-04-27 18:16:57