this是Javascript語言的一個關鍵字。
隨着函數使用場合的不同,this的值會發生變化。但是有一個總的原則,那就是this指的是,調用函數的那個對象。
1.this指向的形式4種
a.如果是一般函數,this指向全局對象window;
b.在嚴格模式下"use strict",為undefined.
c.對象的方法里調用,this指向調用該方法的對象.
d.構造函數里的this,指向創建出來的實例.
定義一個_this變量來存儲this值,使全局對象里面的this 指向person 的this
this最近的函數是全局對象setTimeout
var person = {
name: "shafee",
age: 20,
say: function () { // 對象的屬性是函數,就叫函數的方法
console.log(this.name); // object shafee
}
};
person.say();
var name = "Tom";
var body = document.getElementById("body");
body.onclick = function () {
console.log(this.name); // window Tom
}
var fn = person.say;
fn(); // window Tom
|
|
2. 改變this指向的方式
以下屬於函數的方法
改變this的指向並且執行調用函數
.call(), call(thisScope, arg1, arg2, arg3...)
.apply(), apply(thisScope, [arg1, arg2, arg3...]);兩個參數
而bind 改變this的指向,返回的是函數
.bind() bind(thisScope, arg1, arg2, arg3...)
call,可以傳入多個參數,改變this指向后立刻調用函數
apply,可以傳入數組
bind改變this指向后,返回的是函數
----------------------------------------------------------------------