Reputation: 43843
If I do this in javascript
var A = function() {
alert(this.foo);
};
A["foo"] = "bar";
A();
I expect to alert bar
but I get undefined, does anyone know how I can make this work?
Thanks
Upvotes: 0
Views: 110
Reputation: 3765
var A = function() {
alert(this.foo);
};
A["foo"] = "bar";
A.call(A);
or
var A = function() {
};
A.prototype.alert = function () {
alert(this.foo);
}
var a = new A();
a["foo"] = "bar";
a.alert();
Upvotes: 0
Reputation: 522135
this
refers to the "parent" object of the function, not the function itself. There's no parent in the expression A()
. To "make that work", you'd have to explicitly pass A
as the this
value:
A.call(A);
The way it's usually meant to work is this:
var A = {
alert: function () {
alert(this.foo);
}
};
A.foo = 'bar';
A.alert();
The A
from A.alert()
is used as this
value inside alert()
.
Upvotes: 1
Reputation: 943586
The value of this
is the object upon which the method was called (unless you make use of the new
operator or something like call
or bind
). Since you didn't call the function as a method then it is the default object (window
in a browser) unless you are in strict mode.
The only reference you have to the function in scope is A
, so you can only access it via alert(A.foo)
.
If you had used a named function expression:
var A = function myFunction () {
then you would have had the variable myFunction
locally scoped to that function which you could use instead of A
.
Upvotes: 1