简体   繁体   English

javascript中的范围以访问私有变量

[英]Scope in javascript to access a private variable

a = function (){
    var b = 10;
    var k = function(){
        console.log(b);
    }();
}();

The above code will print 10. 上面的代码将打印10。

var k = function(){
    console.log(b);
}
var a = function (){
    var b = 10;
    k();
}();

This code will print undefined . 此代码将打印 undefined

Is it possible to print 10 instead? 可以打印10吗? Like binding the scope to k before calling it. 就像在调用它之前将范围绑定到k一样。

As @Derek answered, you can obviously pass an argument. 正如@Derek回答的那样,您显然可以传递参数。

Aside from that, you can't transfer or change variable scope, but you can directly manipulate calling context. 除此之外,您不能转移或更改变量范围,但可以直接操纵调用上下文。

As such, you can set b as the property of an object, and set that object as the calling context of whatever function you're calling. 这样,您可以将b设置为对象的属性,并将该对象设置为所调用函数的调用上下文。

var k = function(){
    console.log(this.b);
}
var a = function (){
    var obj = {b:10};
    k.call(obj);
}();

The .call() method invokes the k function, but sets the first argument you provide as the calling context of the called function. .call()方法调用k函数,但是将您提供的第一个参数设置为被调用函数的调用上下文。

In fact, you don't technically need to use an object. 实际上,从技术上讲,您不需要使用对象。 You could directly set the number as the value to use... 您可以直接将数字设置为要使用的值...

var k = function(){
    console.log(this);
}
var a = function (){
    var b = 10;
    k.call(b);
}();

In strict mode, you'll get the number, but in non-strict, you'll get the Number as its object wrapper. 在严格模式下,您将获得数字,但在非严格模式下,您将获得数字作为其对象包装。

Really? 真? What have you tried? 你尝试了什么?

var k = function(b){
    console.log(b);
}
var a = function (){
    var b = 10;
    k(b);  //Done.
}();

Why does it give you undefined in your second example is because b is not defined. 为什么在第二个示例中undefined它是因为b未定义。 You have to define it first before using the variable b . 您必须先定义它,然后才能使用变量b

var k = function(b){ //<--There, defined. Mission accomplished.

Access into the scope can be granted through eval . 可以通过eval授予对范围的访问权限。

var a = (function() {
    var b = 10;
    return {
        eval: function(s) {
            return eval(s);
        }
    };
})();

var k = function() {
    console.log(a.eval("b"));
};

k();
​

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

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