今天因爲時間有些緊,咱們來討論一下this指向問題吧,相信這個問題也困擾了很多同窗,面試的時候,通常都會有這樣的基礎問題,但願你們多多點贊,來鼓勵一下小弟,小弟這廂有禮了哈哈。。。面試
this 是一個關鍵字,它表明函數運行時,自動生成的一個內部對象,只能在函數內部使用。bash
做爲純粹的函數調用, this指向全局對象;app
function fn () {
console.log(this);
}
fn() // Window
var fn = function() {
console.log(this);
};
fn(); // Window
(function(){
console.log(this);
})(); //Window
function fn1(){
function fn2() {
console.log(this)
}
fn2();
}
fn1(); //Window
複製代碼
做爲構造函數被調用, this指向新的對象(new 會改變this的指向);函數
// 【在構造函數中this指向當前建立的對象】
function Student(name,age) {
this.name = name;
this.age =age;
}
Student.prototype.sayHi = function() {
console.log('我叫' + this.name);
};
var stu1 = new Student('張三',10);
var stu2 = new Student('李四',10);
複製代碼
做爲對象的方法調用, this指向調用對象;ui
//借用上面的例子
stu1.sayHi();
stu2.sayHi();
複製代碼
箭頭函數的this指向是外部的第一個純粹函數(其實箭頭函數是沒有this指向的)。this
function a() {
return () => {
return () => {
console.log(this)
}
}
}
console.log(a()()()) //Window
複製代碼
定時器中的this指向Windowspa
setTimeout(function(){
console.log(this)
},1000); //Window
複製代碼
事件處理程序中this的指向事件源prototype
// 【在事件處理程序中,this指向事件源】
document.onclick = function() {
console.log(this);
};
複製代碼
語法:函數名.call(調用者,參數1...)code
做用:函數被借用時,會當即執行,而且函數體內的this會指向借用者或調用者對象
代碼
function fn(name, age) {
this.name = name;
this.age = age;
}
// 對象字面量
var obj = {};
fn.call(obj, '李四', 11);
複製代碼
function fn(name, age) {
this.name = name;
this.age = age;
}
// 對象字面量
var obj = {};
fn.apply(obj, ['李四', 11]);
複製代碼
語法:函數名.bind(調用者,參數1...)
做用:函數被借用時,不會當即執行,而是返回一個新的函數。須要本身手動調用新的函數。
代碼
function fn(name, age) {
this.name = name;
this.age = age;
}
// 對象字面量
var obj = {};
fn.bind(obj, '李四', 11);
複製代碼