简体   繁体   English

javascript类方法封装问题

[英]javascript class method encapsulation issue

I'm pretty new with javascript and I think this is a dumb question but I don't know how to search my issue on google. 我对javascript很陌生,我认为这是一个愚蠢的问题,但我不知道如何在Google上搜索我的问题。

I have a "class" like that : 我有一个这样的“班级”:

function Myclass(){}

Myclass.prototype.method1() = function(){

    whatever.onload = function(){
      this.method2();
    }

};

Myclass.prototype.method2() = function(){};

My problem is that "this" isn't related to my class anymore. 我的问题是“ this”与我的课程不再相关。 In this anonymous function scope, I can't reach my method2. 在此匿名函数作用域中,我无法达到method2。

How can I solve this issue ? 我该如何解决这个问题?

Thanks for your advices. 感谢您的建议。

The simplest way is like this: 最简单的方法是这样的:

Myclass.prototype.method1 = function(){
    var self = this;
    whatever.onload = function(){
      self.method2();
    }
};

The variable self remains in existence even after method1 finishes executing such that the onload function declared with method1 can still access it later. 即使在method1完成执行后,变量self仍然存在,以便method1声明的onload函数以后仍可以访问它。 (For more information about this, google "JavaScript closures".) (有关此的更多信息,请谷歌“ JavaScript闭包”。)

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

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