What is a best practice for ensuring “this” context in Javascript?

后端 未结 8 1431
刺人心
刺人心 2021-02-14 20:37

Here\'s a sample of a simple Javascript class with a public and private method (fiddle: http://jsfiddle.net/gY4mh/).

function Example() {
    function privateFun         


        
8条回答
  •  梦如初夏
    2021-02-14 20:51

    I would say the proper way is to use prototyping since it was after all how Javascript was designed. So:

    var Example = function(){
      this.prop = 'whatever';
    }
    
    Example.prototype.fn_1 = function(){
      console.log(this.prop); 
      return this
    }
    
    Example.prototype.fn_2 = function(){
      this.prop = 'not whatever';  
      return this
    }
    
    var e = new Example();
    
    e.fn_1() //whatever
    e.fn_2().fn_1() //not whatever
    

    Here's a fiddle http://jsfiddle.net/BFm2V/

提交回复
热议问题