一、this指向
1、普通函數(shù)中this指向window
function test() {
console.log(this) // window
}
2、對象中調(diào)用函數(shù),this指向調(diào)用函數(shù)的對象。如果先對函數(shù)作賦值,那么調(diào)用函數(shù)的變量對象時,this指向window。
let obj = {
age: 18,
say() {
console.log(this)
}
}
obj.say() // obj
let fn = obj.say()
fn() // window
3、構(gòu)造函數(shù)中,this指向?qū)嵗鰜淼膶ο?/p>
function Person(name) {
this.name = name
console.log(this) // Person {name: "xiaohong"}
}
let pp = new Person('xiaohong')
4、call、apply、bind中this指向第一個參數(shù)
let obj = {
name: 'lisi',
say(){
console.log(this)
}
}
let obj1 = {
name: 'wangwu'
}
obj.say.call(obj1) // {name: 'wangwu'}
obj.say.bind(obj1)() // {name: 'wangwu'}
5、箭頭函數(shù)中this指向調(diào)用這個函數(shù)的外層對象
let obj2 = {
name: 'wangwu',
say: () => {
console.log(this)
}
}
obj2.say() // window
二、箭頭函數(shù)的缺點(diǎn)
1、沒有arguments
let obj3 ={
// say: function() { //[1,2]
say = () => { // 報錯
console.log(arguments)
}
}
obj3.say(1,2)
2、原型鏈上不能使用
function Person(name, age) {
this.name = name
this.age = age
}
Person.prototype.say = () => { // undefind
// Person.prototype.say = function() {
console.log(this.name, this.age) // 'lisi', 18
}
let p = new Person('lisi', 18)
p.say()
3、構(gòu)造函數(shù)中不能使用箭頭函數(shù)
let Person = (name, age) => {
this.name = name
this.age = age
}
let p = new Person('zhangsan', 3)
console.log(p) // 報錯
4、call、apply、bind不能改變this指向
let obj5 = {
name: 'lisi',
say: () => {
console.log(this)
}
}
let obj6 = {
name: 'wangwu'
}
obj5.say.call(obj6) // window
三、箭頭函數(shù)優(yōu)點(diǎn)
1、簡明語法
const l1 = [1,2,3,4,5]
const l2 = l1.map(function(i) {
return i *2
})
console.log(l2) // [2, 4, 6, 8, 10]
const l3 = l1.map((i) => {
return i *2
})
2、隱式返回
const l4 = l1.map((i) => {i *3})
3、this指向外層對象