Context scope of this object in JavaScript

1: In function call mode, for example:

     function ninja(){};

     ninja();

     var samurai = function ();

     samurai();

The this scope global context of this function is the Windows object

2: In method invocation pattern, for example:

     var o = {};

     o.whatever = function () {};

     o.whatever();

The context of the this scope of this function is this object

3: In the constructor call mode, for example: (Note: the first letter of the constructor is capitalized)

     function Ninja(){

         this.skulk = function(){ return this;}

     }

     var ninja1 = new Ninja();

     var ninja2 = new Ninja();

     assert(ninja1.skulk() === ninja1, "The 1st ninja is skulking");

     assert(ninja2.skulk() === ninja2, "The 2nd ninja is skulking");

The context of this scope is the new object created for

4: In apply/call calling mode, for example:

     function forEach(list, callback){

          for (var n = 0; n < list.length; n++){

               callback.call(list[n], n);

          }

     }

     var list = ['shuriken', 'katana', 'nunchucks'];

     forEach(list,function(index){

          console.log(index);

          console.log(this);

          assert(this == list[index], "Got the expected value of “+ list[index]);   

     })

The context of this scope can be any object we specify

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325900707&siteId=291194637