JS中有兩種模式,嚴格模式和非嚴格模式,我們看看這兩種模式下this的情況
console.log(this);
// Window
'use strict'
console.log(this);
// Window
//兩種模式下this的指向是相同的
函數內的this
- 普通模式
function fn () {
console.log(this); //window
console.log(this === window); //true
}
fn()
- 嚴格模式
'use strict'
function fn () {
console.log(this); //undefined
console.log(this === window); //false
}
fn()
不同模式下,函數內this的指向是不同的
call, apply, bind
- js中有方法可以改變this的指向,我們分別調用試試,call和apply的不同在于參數的不同,apply接受一個類數組對象,call用
,
傳入多個參數 - call,apply
'use strict'
function thisWithCall () {
console.log(this); //{name: 'harry'}
console.log('name is', this.name); //name is harry
}
thisWithCall.call({name : 'harry'})
function thisWithApply () {
console.log(this); //{name: 'potter'}
console.log('name is', this.name); //name is potter
}
thisWithApply.apply({name : 'potter'})
- bind創建一個新函數,此過程中改變this的指向,我們通過調用新函數使用改變的this
function thisWithBind () {
console.log(this); //henry
console.log('name is', this); //name is henry
}
let newBind = thisWithBind.bind('henry')
newBind()
箭頭函數的this
- 箭頭函數沒有this,也不能設置this,他們使用外層作用域中的this指向
const obj = {
name : 'harry',
getArrowName: () => {
console.log(`name is ${this.name}`); //name is
console.log(this); //window
},
getNormalName: function () {
console.log(`name is ${this.name}`); //name is harry
console.log(this); //{name: 'harry', getArrowName: ?, getNormalName: ?}
}
}
obj.getArrowName()
obj.getNormalName()
箭頭函數的this指向了全局作用域window,普通函數指向了obj的塊級作用域
const count = {
count : 0,
addCount1 : function () {
setTimeout(() => {
console.log(this.count++); //0
console.log(this); //{count: 1, addCount1: ?, addCount2: ?}
})
},
addCount2: function () {
setTimeout(function () {
console.log(this.count++); //NaN
console.log(this); //window
})
}
}
count.addCount1()
count.addCount2()
setTimeout的回調中,箭頭函數的this指向了count塊級作用域,普通函數指向了全局作用域
對象方法的this
var obj = {
name : 'harry',
getName : function() {
return this
}
}
console.log(obj.getName()); //{name: 'harry', getName: ?}
//this指向調用自己的對象
構造函數內的this
'use strict'
function Person (name, age) {
this.name = name
this.age = age
this.getPerson = function () {
return `我是${this.name},我${this.age}歲了`
}
this.returnThis = function () {
return this
}
}
var p = new Person('harry', 18)
console.log(p); //Person {name: 'harry', age: 18, getPerson: ?, returnThis: ?}
console.log(p.getPerson()); //我是harry,我18歲了
console.log(p.returnThis()); //Person {name: 'harry', age: 18, getPerson: ?, returnThis: ?}
構造函數內的this,指向其創建的實例
事件中的this
<button id="btn">點擊</button>
//普通函數
var btn = document.querySelector('#btn')
btn.addEventListener('click', function () {
console.log(this); //<button id="btn">點擊</button>
})
//箭頭函數
var btn = document.querySelector('#btn')
btn.addEventListener('click', () => {
console.log(this); //window
})
按鈕點擊事件的this指向了按鈕本身(普通函數),箭頭函數中指向了全局window