I'm developing a firefox extension and I think I've now hit a basic misunderstanding regarding Javascript, with the 'prototype' concept to be exact. Consider the following minimal example, notice the differences when I set the variables this.demo and this.test:
var Example = new Array();
Example.Foo = function() {
this.test = null;
this.demo = "World";
};
Example.Foo.prototype = {
initialize : function(resource) {
this.test = "Hello";
this.display();
},
display : function() {
alert(this.test + " " + this.demo);
},
}
window.addEventListener(
"load",
function() {
window.obj = new Example.Foo();
obj.initialize();
},
false
);
When opening Firefox I get the expected output:
Hello World
This works always fine this way as long as a call display() 'within' the js source file. However, when I call display() via corresponding click from a menu entry, e.g.:
...
<menupopup id="menu_ToolsPopup">
<menuitem label="Example" oncommand="obj.display();"/>
</menupopup>
...
I get:
null World
initialize() has been called beforehand, of course.
I'm still rather new to Javascript and work with existing code. I'm therefore quite confused with the current behavior. What is the best solutions to get is working?
Because this
is referencing to the object that call the method.
var MyObject= new function(){
this.value="Hello World!";
this.display=function(){
alert(this.value);
}
}
<input type="button" value="Foo Bar!" onclick="MyObject.display()"> //Foo Bar!
this exemple will alert "Foo Bar!" instead of "Hello World!"
to prevent this unexpected situations you can add a "Checkpoint" using var that=this;
var MyObject= new function(){
var that=this; // <--- reference to actual object
this.value="Hello World";
this.display=function(){
alert(that.value);
}
}
<input type="button" value="Foo Bar!" onclick="MyObject.display()"> //Hello World!
this will alert "Hello World!" 'value' from the MyObject not the 'value' of the tag.
.
maybe this other situation help you to understand
<img scr="dog.gif" title="Little Dog" onclick="alert('This is a '+this.title)">
"This is a Little Dog"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With