this的指向
1.直接調(diào)用,指向window
var x=1;
console.log(this.x);
//輸出 1
2.在函數(shù)里調(diào)用沉噩,指向window
var x=1;
function fn(num){
var x=2;
console.log(this.x);
}
fn();
//輸出 1
3.在構(gòu)造函數(shù)里用new調(diào)用闹丐,指向創(chuàng)建的新實例對象
function fn(){
console.log(this);
}
let a=new fn();
//輸出 {}(指向?qū)ο骯)
4.在對象的方法里調(diào)用,指向調(diào)用它的對象
function fn(num){
this.x=num;
this.fn1=function(){
console.log(this.x)
}
}
let a=new fn(3);
a.fn1();
//輸出 3
改變this的指向
1.用new調(diào)用函數(shù)昆禽,改變指向new的實例對象
function fn(){
console.log(this);
}
let a=new fn();
//輸出 {}(指向?qū)ο骯)
2.bind
function fn(){
console.log(this.name);
};
var obj={
name:'jack',
};
var b=fn.bind(obj);
b();
3.call
function fn(name){
this.name=name;
this.fn1=function(){
console.log(this.name);
}
};
var obj={};
fn.call(obj,'jack');
console.log(obj.name);
obj.fn1();
4.apply
function fn(name,age){
this.name=name;
this.age=age;
this.fn1=function(){
console.log(this.name);
}
};
var obj={};
fn.apply(obj,['jack',18]);
console.log(obj.age);
obj.fn1();
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者