The use of “this” is confusing me in JavaScript

后端 未结 5 398
既然无缘
既然无缘 2020-12-04 13:38

Working with the JavaScript one of the confusing thing is when using this

var x = {  
  ele : \'test\',
  init : function(){ 
    alert(this.ele)         


        
5条回答
  •  南方客
    南方客 (楼主)
    2020-12-04 14:07

    It's not about performance, it's about accessing a property of a specific instance of an object:-

    x.init()
    

    Would not display 'test' if you hadn't use this in the function.

    Effectively the above line is the same as:-

    x.init.call(x);
    

    the first paramater in the use of call is assigned to this when the function is executed.

    Now consider:-

    var fn = x.init;  //Note no () so the function itself is assigned to the variable fn
    fn();
    

    Now you get nothing in the alert. This because the above is effectively:-

    fn.call(window);
    

    In browser hosted Javascript the window object is synonymous with the global object. When a function is called "in the raw" then the this defaults to the global object.

    The classic error is doing something like this:-

    var x = {
       ele: 'test';
       init: function(elem) { 
          elem.onclick = function() { alert(this.ele); }
       }
    }
    x.init(document.getElementById('myButton'));
    

    However this doesn't work because the function attached to the onclick event is called by the browser using code like:-

    onclick.call(theDOMElement)
    

    Hence when the function is running this isn't what you think it is.

    My usual solution to this situation is:-

    var x = {
       ele: 'test';
       init: function(elem) {
          var self = this; 
          elem.onclick = function() { alert(self.ele); }
          elem = null;
       }
    }
    x.init(document.getElementById('myButton'));
    

    Note the elem = null is IE memory leak work-around.

提交回复
热议问题