如何在Javascript类中从"私有方法"访问"公共变量"

Los*_*ode 4 javascript html5

首先,请参阅我的代码plz.

function test(){

    this.item = 'string';

    this.exec = function(){
        something();
    }

    function something(){
        console.log(this.item);
        console.log('string');
    }
}
Run Code Online (Sandbox Code Playgroud)

我做了类并调用'exec函数',就像这段代码一样

var t = new test();

t.exec();
Run Code Online (Sandbox Code Playgroud)

但结果是......

undefined
string
Run Code Online (Sandbox Code Playgroud)

我想从一些函数访问test.item.

你有什么解决方案吗?

go-*_*leg 6

您需要调用something,apply以便在以下this内容中正确设置something:

function test(){

    this.item = 'string';

    this.exec = function(){
        something.apply(this);
    }

    function something(){
        console.log(this.item);
        console.log('string');
    }
}
Run Code Online (Sandbox Code Playgroud)

正如@aaronfay指出的那样,这是因为this没有引用new test()创建的对象.你可以在这里阅读更多相关信息,但一般规则是:

如果一个功能上的调用object,然后thisobject.如果函数自己调用(如代码中的情况),则this引用浏览器中的全局对象window.

  • 值得注意的是`function something(){}`改变了`this`关键字的上下文,这就是它不再符合预期的原因.`apply`有效地将`this`的上下文应用于另一个函数. (2认同)