[removed] When and when not to use “this”

前端 未结 4 1903
野的像风
野的像风 2021-02-06 20:23

Im curious when it is needed/best practice to use the keyword this. I understand that this is used when determining a functions this value

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-06 20:50

    'This' is used inside a function and it contains the value of the object that invokes the function.

    For example:

    function a(){
     this.newVariable = 'Phil';
    }
    a();
    console.log(newVariable); //This line would display Phil
    

    In this case, even though we just define newVariable inside the function a(). The object that invokes the function is the global object window, so 'this' points to window and this.newVariable is at the global scope.

    Another example would be:

    var c={
      log:function(){
        this.name = 'Phil';
       }    
    }
    

    In this case, 'this' points to the object c, since the log function will be invoked by c.

    We have more tricky cases in the use of the object 'this' in Javascript. This is a good article to grasp the concept: http://javascriptissexy.com/understand-javascripts-this-with-clarity-and-master-it/

提交回复
热议问题