将变量传递给函数范围

时间:2016-11-07 05:05:11

标签: javascript

是否可以在不传递参数的情况下以其他方式执行以下操作?

var f = function(){
    console.log(v);
}

var original = f;

f = function(){
    var v = "test";
    original();
};

// the following line is called by 3rd party code
f();  // it errors out here - v is not defined

3 个答案:

答案 0 :(得分:1)

var v设为全球变量

var v ;
var f = function(){
  v="new test"
    console.log(v);
}

var original = f;

f = function(){
     v = "test";
    original();
};

f();//f function
original();//original function also working

答案 1 :(得分:0)

使用可以在这里使用JavaScript Closures

function f() {
    var v = 'test';
    return (function () {
        console.log(v)
    })();
}

答案 2 :(得分:0)

另一种方法:

var f = function(){
    console.log(arguments[0]);
};

f = f.bind(null, 'test');

f();