简体   繁体   English

如何正确传递我的范围以查找变量

[英]How do i pass my scope correctly to look for variables

i was trying to use the javascript APPLY function to pass scope from 1 function to another, but it seems that i might be doing it wrong? 我试图使用javascript APPLY函数将范围从1个函数传递到另一个函数,但似乎我可能做错了吗?

Here is a fiddle if you need it: http://jsfiddle.net/C8APz/ 如果你需要它,这是一个小提琴: http//jsfiddle.net/C8APz/

Here is my code: 这是我的代码:

function a(){
    var x = "hello";
    b.apply(this, []);
}

 function b(){
    console.log("x: ", x);
}

a();

i was thinking that while the scope is passed, the variables / variable reference are not. 我认为在传递范围时,变量/变量引用不是。

Is there a way to do something like this without defining Globals? 有没有办法在没有定义Globals的情况下做这样的事情?

Should i add the data to the actual part of it, such as this.x = x; 我应该将数据添加到它的实际部分,例如this.x = x; ? and then in the other function just fetch it? 然后在另一个函数中只是获取它? var x = this.x;

function a(){
    var x = "hello";
    this.x = x;
    b.apply(this, []);
}

 function b(){
    var x = this.x;
    console.log("x: ", x);
}

a();

Edit: It seems that the second example assigns in the global scope, which isnt good, and with the scope, i was attempting to pass an understanding of context to. 编辑:似乎第二个示例分配全局范围,这不是好的,并且在范围内,我试图将对上下文的理解传递给。 It seems that you really have to define a context before you pass it, otherwise, for the most part this refers to window 看来你必须在传递它之前定义一个上下文,否则,大多数情况下指的是window

You cannot pass scope around. 你无法通过范围。

You can either move the function declaration for b inside the function declaration for a so that the scope is right to start with, or you can pass the variables you care about using arguments. 您可以移动的函数声明为b函数声明中为a ,这样的范围是正确的开始,或者你可以通过你所关心的变量有关使用参数。


function a(){
    var x = "hello";
    b();

    function b(){
        console.log("x: ", x);
    }
}

a();

function a(){
    var x = "hello";
    b(x);
}

function b(x){
    console.log("x: ", x);
}

a();

Declare var x; 声明var x; out of the function body... 离开功能体...

var x;
function a(){
    x = "hello";
    b.apply(this, []);
}

function b(){
    //a.apply(this,[]);
    console.log("x: ", x);
}

a();

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

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