Skip to content Skip to sidebar Skip to footer

Is It Possible For A Function Called From Within An Object To Have Access To That Object's Scope?

I can't think of a way to explain what I'm after more than I've done in the title, so I'll repeat it. Is it possible for an anonymous function called from within an object to have

Solution 1:

Should be this.Foo:

var test = new myObj(function() {
    var test = new this.Foo();
    test.saySomething("Hello world");
});

http://jsfiddle.net/grzUd/5/

Or alternatively using with:

var test = new myObj(function() {
    with (this) {
        var test = new Foo();
        test.saySomething("Hello world");
    }
});

http://jsfiddle.net/grzUd/6/


Solution 2:

Change var test = new Foo(); to var test = new this.Foo();.

Edit: Or you could pass it as a parameter.

function myObj(testFunc) {
    this.testFunc = testFunc;

    var Foo = function (test) {
        this.test = test;
        this.saySomething = function(text) {
            alert(text);
        };
    };

    this.testFunc(Foo);
}

var test = new myObj(function(Foo) {
    var test = new Foo();
    test.saySomething("Hello world");
});

Solution 3:

You seem to be confused about the difference between identifier resolution on the scope chain and property resolution.

Foo is a property of an instance of myObj (i.e. it's an object property). Calling new Foo will resolve Foo as a variable on the scope chain, which isn't the right place to look for it. That's why Petah's answer tries to use with, to put the object properties of the this object on the scope chain.


Post a Comment for "Is It Possible For A Function Called From Within An Object To Have Access To That Object's Scope?"