クラスの関数メンバーでthis
オブジェクトを使用します。この関数は、クラスのインスタンスによって異なる場合があります。それは正常に動作しますが、Google Closure Compilerは私に警告を送信し、私はそれを正しくやっていないと思います。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);}
^
感謝あなたの助けにたくさん!あなたの例から
は、なぜあなたはプロトタイプにこれらのメソッドを取り付けることがwouldntは:
は、この警告を黙らするためには、単に「この」オブジェクトの種類コンパイラに指示する必要がありますか? – Tejs私はそれについて心配しません。あなたがやっていることは、プロトタイプから継承された振る舞いをオーバーライドするための完全に有効な方法です。 – Prestaul
[Closure Compiler Warning 'グローバルなこのオブジェクトの危険な使用 'の可能な複製?](http://stackoverflow.com/questions/5301373/closure-compiler-warning-dangerous-use-of-the-global-this-オブジェクト) –