Calling method inside another method in javascript?

前端 未结 4 1545
执念已碎
执念已碎 2021-02-07 21:21

I am having a JavaScript namespace say

A={

  CA: function() {
    this.B();
  },
  B: function() {
    var test=\'test\';
    var result=\'t1\';

    C: functi         


        
4条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-07 21:51

    You have to be careful when you use this to identify anything in Javascript because each time you change scope "this" changes.

    Assigning the 'this' reference to it's own variable helps get around this.

    var a = new function() {
        var self = this;
    
        self.method = function() { alert('hiya'); };
    
        var b = function() {
            this.method(); // this isn't 'a' anymore?
            self.method(); // but 'self' is still referring to 'a'
        };
    
    };
    

提交回复
热议问题