0

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

1
  • 1
    var A = function() { alert(this.foo); }; A.prototype.foo = "bar"; var x = new A(); Commented Feb 29, 2016 at 16:22

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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().

Comments

0
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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.