I want to use the this object in a function member of a class. The function can be different depending of the instance of the class. It works fine but Google Closure Compiler sends me warnings which makes me think I am not doing it properly.
Hence my question: what is the correct way of using this in a function that is neither a prototype nor a constructor?
If there is no, what should I do instead of trying to use this there?
Here is an illustration of what I am trying to do:
/** @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();
While compiling I am getting this warning and could not find a way to work around it:
JSC_USED_GLOBAL_THIS: dangerous use of the global this object at line 11 character 57
formalAlert.myAlert = function() {alert("Good morning" + this.name);}
^
Thanks a lot for your help!
From your example:
Creates a new static property on formalAlert which shadows (not replaces) the prototype. While still perfectly valid javascript, it is important to realize that the compiler correctly sees these as different properties.
To silence this warning, you simply need to tell the compiler the type of the ‘this’ object: