简体   繁体   中英

JavaScript: store function in an object, but execute it in local context

I have an object like this:

objectx = {
    1: {
        name: "first",
        loadFunction: function() { 
            $(target).load("http://stackoverflow.com #question", function() {
                // do something else
            });
        }
    },
    2: {
        name: "second",
        loadFunction: function() { 
            $(target).load("http://stackoverflow.com #answer", function() {
                // do something else
            });
        }
    }
}

When I call the functions with objectx[1].loadFunction(), they don't have the local context, so I would have to pass everything as argument or make my variables global. For example:

function doSomething() {
    var target; // this variable holds a reference to a DOM object

    objectx[1].loadFunction()
}

target is not defined

How do I execute the functions so that they are aware of the context they are called from?

This is not possible (the way you do it), due to how lexical scope works in JavaScript.

You want a function argument, plain and simple. Writing functions that depend on global state is bad style anyway.

var objectx = {
    1: {
        name: "first",
        loadFunction: function(target) { 
            $(target).load("http://stackoverflow.com #question", function() {
                // do something else
            });
        }
    }
}

and

function doSomething() {
    var target; // this variable holds a reference to a DOM object

    objectx[1].loadFunction(target);
}

Done.

This is impossible in JavaScript. JS uses lexical scoping . What you seem to be looking for is dynamic scope.

The best you can do is either pass arguments, define it in scope, or use a global variable (less than recommended).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM