Calling method inside another method in javascript?

前端 未结 4 1522
北荒
北荒 2021-02-07 21:05

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:57

    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'
        };
    
    };
    

提交回复
热议问题