Tuesday, 23 June 2015

javascript basic again -- this




----------
This

This is the reference of what calls it (before the ".").  A call without ".", "this" is window.

var test = "cat";
var myFunc = function (a,b,c){
   alert(this.test);  //this is window
}

myFunc();


----------
apply()

var test = "cat";
var myFunc = function (a,b,c){
   alert(this.test);  //this is window
}

var xxx = {
     test: "aaaaa"
}

myFunc.apply(xxx,[1,2,3])

This code will alert "aaaaa"

When you call apply, "this" this the first paramter --- xxx.

----------
closure():


var func  = function (){
   var a = "aaa"
    //"this" here is window   //place lala
   var inner_fnc = function (){
         var a = "xxxxa"
         // "this" here is window as well.  // place lblb
    }
   inner_func()
}

func();

Note: closure doesn't have anything different. you still need check the "caller" before "."

there is nothing before "." when you call func(), so it is "window" in "place lala"

there is nothing before "." when you call inner_func(), so it is "window" in "place lblb"


---

With above code, if I run below code. "this" in the "place lala" is "aaa", "this" in "place lblb" is still "window".  You can use the same rule to explain it. no difference.

var aaa = function(){};

var aa = new aaa();
aa.xx = func;
aa.xx();



No comments:

Post a comment