I have been doing some JavaScript development and I encountered this problem. Consider the following code
var obj = {};
obj.bind = function () {
console.info(this);
};
obj.bind();
I’m running the code on the FireBug JavaScript console. The expected result is that this displays a reference to the object in the console.
It actually displays undefined.
But, when I make this change to my code
var obj = {};
obj.bind = function () {
this.x = 'x';
console.info(this);
};
obj.bind();
Now the console displays the expected value of this, which is a reference to the obj object.
Why does this happen?
undefinedis the return value of the function, which you’ll get because you’re not returning a value explicitly.In both Chrome and Firebug, it correctly displays the Object in the console before the return value
undefined.So if you do:
…you should see something like:
If Firebug is not displaying the Object when it is empty, you may need to check to make sure you’re using the most current version.