简体   繁体   English

JavaScript:将函数存储在对象中,但在本地上下文中执行

[英]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. 当我使用objectx [1] .loadFunction()调用函数时,它们没有本地上下文,因此我必须将所有内容都作为参数传递或使变量全局化。 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. 由于词汇范围在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. 这在JavaScript中是不可能的。 JS uses lexical scoping . JS使用词法作用域 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). 最好的办法是传递参数,在范围内定义它或使用全局变量(不建议使用)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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