webveuje/js/kejian/day4.md
2021-02-02 17:27:36 +08:00

111 lines
2.9 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# this 指向
## 什么是 this
this 是执行期上下文中的一个属性,设计目的是在函数体内部指代函数当前的运行环境,以方便引用当前环境的其他变量
## 判断this指向的规则
**谁(对象)调用 就指向谁**
如果没在对象里面 this就指向全局window全局对象
如果在对象中this指代的是当前对象实例
箭头函数例外他的函数内部没有this 在执行到this的时候会去找外部对象 所以 箭头函数的this最终就指向他外一层的对象 当他只有一层的时候 this会指向全局对象 window
思考下面的代码 会输出什么
```
var aaa=1;
var c=3
function fn(){
aaa=6
console.log(this.aaa)
}
var obj={
aaa:222,
fn:function(){
console.log(this.aaa)
}
fn1:()=>{
console.log(this.aaa)
}
}
fn()
obj.fn() //222
obj.fn1() //1
console.log(this.c) //this==> window
console.log(c) = console.log(window.c)
```
# call 和 apply (改变this指向)
### call
作用 改变this的指向
语法: B.方法名.call(A,n,m...)
这个方法本来是B拥有的方法中的this 指向的也是B
执行完这句call 之后, 方法中的this 指向A
所以说A用了这个方法
```
var cat={
name:"大喵",
run:function(){
console.log("我会跑")
},
eat(){
console.log("我在吃东西")
}
};
var dog={
name:"大汪",
bark(){
console.log("汪汪汪")
},
paqiang(){
console.log(this)
console.log("我能爬墙")
}
}
// 大喵需要借用大汪的paqiang的技能
dog.paqiang.call(cat)
dog.paqiang()
//让别人用自己的技能
dog.paqiang.call(cat)
paqiang 是dog有的技能
this指向也变成猫了
```
### apply
apply 的作用和call 是完全一样的都是改变this的指向
语法: B.方法名.apply(A,[n,m...])
这个方法本来是B拥有的方法中的this 指向的也是B
执行完这句apply 之后, 方法中的this 指向A
所以说A用了这个方法
上面的问题也可以用下面的方式解决:
```
var cat={
name:"大喵",
run:function(){
console.log("我会跑")
},
eat(){
console.log("我在吃东西")
}
};
var dog={
name:"大汪",
bark(){
console.log("汪汪汪")
},
paqiang(m,n){
console.log(this)
console.log(m,n,"我能爬墙")
}
}
// 大喵需要借用大汪的paqiang的技能
// dog.paqiang.call(cat,1,2) 这是call实现的
dog.paqiang.apply(cat,[1,2]) //这是用apply实现的
dog.paqiang()
```