1,this在函数指向
- 在绝大多数情况下,函数的调用方式决定了 this 的值(运行时绑定)。
this
是 JavaScript 语言的一个关键字。- 它是函数运行时,在函数体内部自动生成的一个对象,只能在函数体内部使用
function fun1() {
this.p = 1;
}
上面代码中,函数fun1运行时,内部会自动有一个this
对象可以使用。
那么,this
的值是什么呢?
函数的不同使用场合,this
有不同的值。总的来说,this
就是函数运行时所在的环境对象。下面分四种情况,详细讨论this
的用法。
01在普通函数中
通常 谁调用函数,谁是函数中的this
在普通函数中的this : window
在事件注册中
dom1 事件注册中:事件对象( dom)
<h1>javascript中this</h1>
<p onclick="fun1(this)">在普通函数中</p>
<p class=" dom" >事件注册dom</p>
<p>在对象中</p>
<p>全局函数中</p>
<p>箭头函数中</p>
<p>构造函数中</p>
<p>call- apply - bind中</p>
<p>new关键字做了哪些事情</p>
<script>
//谁调用函数,谁是函数中的this
// 01在普通函数中的this : window
// 1.1 在html中调用:window
// 1.2 dom1 事件注册中:事件对象( dom)
var dom = document.querySelector(".dom");
dom. onclick = fun2
function fun2(){
console.log(this);
}
function fun1(el){
console.log(this,el)
}
</script>
02对象中的this:对象本身
03全局方法中的this:window[setInterval,setTimeout]
var age =50;
var obj={
name:"mumu",
age:18,
say:function(){
console.log(this.age)
},
grow:function(){
setInterval(function(){
this.age++;
console.log(this.age);
},3000)
}
}
obj.grow()
04箭头函数
箭头函数的this是指向上一层作用域的this(obj)
var age =50;
var obj={
name:"mumu",
age:18,
say:function(){
console.log(this.age)
},
grow:function(){
setInterval(()=>{
this.age++;
console.log(this.age);
},3000)
}
}
obj.grow();
05构造函数中this的指向
上一层函数
var age =50;
var obj={
name:"mumu",
age:18,
say:function(){
console.log(this.age)
}
}
// obj.say();
var fn=obj.say;
fn()
06call与apply都是执行一个函数 用第一个参数冒充函数的this
function add(a,b){
console.log(this,a,b);
}
// add(4,5);
// call与apply都是执行一个函数 用第一个参数冒充函数的this
add.call({name:"mumu"},4,5);
// apply参数用的是数组形式
add.apply({name:"mumu",age:18},[8,7]);
var fn=add.bind({eye:2,leg:2},10,5);
fn(10,5);
fn()