js point of this issue

this point, always only be the object!
this point who never depend on which this write! But on the functions which call.
this points to an object, we call context context function, also called the caller of the function.

1: direct call by the function name: this point window

function func(){
    console.log(this);
}   


//① 通过函数名()直接调用:this指向window
func(); // this--->window

2: Through the object function name () call: this points to this object

function func(){
    console.log(this);
}
//② 通过对象.函数名()调用的:this指向这个对象
// 狭义对象
var obj = {
    name:"obj",
    func1 :func
};
obj.func1(); // this--->obj

// 广义对象
document.getElementById("div").onclick = function(){
    this.style.backgroundColor = "red";
}; // this--->div

As a function of an element of the array, the array through standard call: this array points to the

function func(){
    console.log(this);
}
//③ 函数作为数组的一个元素,通过数组下标调用的:this指向这个数组
var arr = [func,1,2,3];
arr[0]();  // this--->arr

Built-in functions as a window function callback function call: this point window (setInterval setTimeout etc.)

function func(){
    console.log(this);
}

//④ 函数作为window内置函数的回调函数调用:this指向window
setTimeout(func,1000);// this--->window
//setInterval(func,1000);

Function as a constructor, when called with the new keyword: this points to a new new object

function func(){
    console.log(this);
}
//⑤ 函数作为构造函数,用new关键字调用时:this指向新new出的对象
var obj = new func(); //this--->new出的新obj

Guess you like

Origin www.cnblogs.com/amysu/p/10951043.html