1 、 在普通函数中::在html结构中同样指向window(在dom 事件注册中:事件对象(dom))
function fun1(el){
console.log(this,el);
}
fun1()
2 、 在对象中的this中: this指向对象本身
var dom = document.querySelector(".dom")
dom.onclick = fun2
function fun2(){
console.log(this);
}
3 、在全局方法中:this指向 window[setInterval,setimout]
grow(){
setInterval(function(){
this.age++;
console.log(this.age)
},3000)
}
grow(){
setInterval(function(){
this.age++;
console.log(this.age)
},3000)
}
4 、在箭头函数中:this指向上一层作用域的this
grow(){
setInterval(()=>{
this.age++;
console.log(this.age)
},3000)
}
4 、在在call-apply-bind中: 冒充this
this指向的是函数call的第一个参数(apply传参方式数组)
bind 把bind的第一个参数作为this,创建一个新的函数
function add(a,b){
console.log(this,a,b);
}
add(4,5)
// call与都是执行一个函数,使用第一个参数进行冒充函数中的this
add.call({name:"qiqi"},4,5)
// apply的传参方式是数组
// add.apply({name:"qiqi",age:"77"},[8,7])
// bind 把bind的第一个参数作为this,创建一个新的函数,并可以指定默认参数
var fn = add.bind({eye:2,leg:2},10,5)
fn(10,5)
fn()
// 把函数简化为参数的这种方式柯里化
5 、构造函数的this指向创建的实例对象
用new操作符创建对象时发生的事情:
1 创建一个Object对象实例。
2 将构造函数的执行对象赋给新生成的这个实例。
3 执行构造函数中的代码
4 返回新生成的对象实例