简体   繁体   English

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

[英]How to access from 'private method' to 'public variable', in Javascript class

First, See my code plz. 首先,请参阅我的代码plz。

function test(){

    this.item = 'string';

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

    function something(){
        console.log(this.item);
        console.log('string');
    }
}

And I made class and call 'exec function', like this code 然后我制作了类并调用“ exec函数”,就像这样的代码

var t = new test();

t.exec();

But result is... 但是结果是...

undefined
string

I wanna access from something function to test.item. 我想从某种功能访问test.item。

Have you any solution? 你有什么解决办法吗?

You need to call something with apply so that this is properly set inside of something : 你需要调用somethingapply ,使this是正确设置里面something

function test(){

    this.item = 'string';

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

    function something(){
        console.log(this.item);
        console.log('string');
    }
}

As @aaronfay pointed out, this happens because this doesn't refer to the object that new test() created. 正如@aaronfay指出的,发生这种情况是因为this并不涉及new test()创建的对象。 You can read more about it here , but the general rule is: 您可以在此处了解更多信息,但一般规则是:

If a function is invoked on an object , then this refers to that object . 如果在一个object上调用了一个object ,则this引用该object If a function is invoked on its own (as is the case in your code), then this refers to the global object, which in the browser is window . 如果一个函数被单独调用(就像您的代码中那样),则this引用的是全局对象,在浏览器中是window

You have many choices, but I recommend the last one. 您有很多选择,但我建议选择最后一个。

var item = 'string'

or 要么

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

or 要么

var that = this;
function something(){
    console.log(that.item);
    console.log('string');
}

this.item in something() isn't what you think it is. something() this.item不是您认为的那样。

The this value is different. this值是不同的。 In this case, it's the global object. 在这种情况下,它是全局对象。

The best solution, in my opinion, is to declare a variable with a reference to this , that can be accessed inside the inner function. 我认为,最好的解决方案是使用this声明一个变量,该变量可在内部函数中访问。


function test() {
    var that = this; // a reference to 'this'

    function something() {
        console.log(that.item); // using the outer 'this'
        console.log('string');
    }

    this.item = 'string';

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

Why not just define something like this: 为什么不只定义如下内容:

Fiddle 小提琴

function test(){

    this.item = 'string';

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

    this.something = function(){
        console.log(this.item);
        console.log('string');
    }
} 

var t = new test();
t.exec();
// output:
// string 
// string

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

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