javascript中的this指向问题
js中的this指向问题
·
this指向问题
函数的this在函数执行时确定的
1.否早函数new 函数名() this指向new出来的对象实例
function Star(name,age){
this.name=name;
this.age=age;
this.sing=function(){
console.log(this.age);
}
}
var a=new Star("yang",12);
a.sing();//12
2.箭头函数的this指向上层作用域
var age = 21;
var obj = {
name: "yang",
age: 18,
sing: ()=>{
var age = 10;
console.log(this.age);
}
}
obj.sing(); //21 箭头函数指向上一级
3.对象中的this指向
var age = 21;
var obj = {
name: "yang",
age: 18,
sing: function(){
var age = 10;
console.log(this.age,this);
}
}
obj.sing(); //18 obj function 指向调用者
4.setTimeout setInterval 里面的this指向 window
var age = 21;
var obj = {
name: "yang",
age: 18,
sing: function() {
setTimeout(function(){
console.log(this.age);
},1000)
}
}
obj.sing(); //21 setTimeout全局方法
5.事件响应函数中的this指向调用者
<body>
<p onclick="fun1(this)">在普通函数中</p>
</body>
<script>
function fun1(el){
console.log(el,this);
}//<p οnclick="fun1(this)">在普通函数中</p> window
</script>
6.call,apply,bind响应的函数this指向第一个参数
function fun(a,b){
console.log(this,a,b);
}
fun.call({b:2},1,2);//{b: 2}b: 2[[Prototype]]: Object 1
fun.apply({b:2},[1,3]);//{b: 2} 1 3
// call apply第一个参数作为this apply的参数以数组的方式传入
var saum=fun.bind({b:2},3,4);
saum();//bind 返回一个新方法 第一个参数 作为新方法的this指向
更多推荐

所有评论(0)