1.this:
全局this -------> window
局部(函数)this -------> 调用其的对象
构造函数this -------> 当前构造函数的实例对象
总之一句话:this指向的是调用者
var name = "Jack";
function hello(){
var name = "Jeff"
console.log(this.name); // Jack
console.log(this); //window
}
hello();
hello()没有调用者,默认this====>window
image.png
var name = "Jack";
var obj = {
name:"Jeff",
fun:function(){
console.log(this.name) //Jeff
}
}
obj.fun(); // window.obj.fun()
函数fun()的调用者是obj,,this===>obj
image.png
var name = "Jack";
var obj = {
name:"Jeff",
fun:function(){
console.log(this.name) // Jack
}
}
var fun = obj.fun;
fun();
fun()无调用者,this===>window
image.png
var name = "Jack";
function fun(){
var name = "Jeff";
fn();
function fn(){
console.log(this.name); //Jack
}
}
fun();
fun()无调用者,this ===>window
image.png
var obj = {
name:"Jeff",
sayName:function(){
console.log(this.name)
},
child:{
name:"Jack",
sayName:function(){
console.log(this.name)
}
},
sayName2:()=>{
console.log(this.name)
}
}
obj.sayName();
obj.child.sayName();
obj.sayName2();
image.png
2.改变this指向
var name = "Jack";
var obj = {
name:"Jeff",
fn1:function(){
console.log(this.name);
console.log(this)
},
fn2:()=>{
console.log(this.name);
console.log(this)
},
fn3:function(){
setTimeout(function(){
console.log(this.name);
console.log(this)
},10)
},
fn4:function(){
setTimeout(()=>{
console.log(this.name);
console.log(this)
},10)
}
}
obj.fn1();
obj.fn2();
obj.fn3();
obj.fn4();
()=>{}可以改变this指向,单独使用使得this ===>window
image.png
call()、apply()、bind()、()=>{}、let _that = this改变this指向
var name = "Jack";
var obj = {
name:"Jeff",
fn1:function(){
setTimeout(function(){
console.log(this.name);
console.log(this)
},10)
}
fn2:function(){
setTimeout(function(){
console.log(this.name);
console.log(this)
}.apply(obj),10)
}
fn3:function(){
setTimeout(function(){
console.log(this.name);
console.log(this)
}.call(obj),10)
}
}
obj.fn1();
obj.fn2();
obj.fn3();
image.png
3、new
new
创建空对象
执行函数
确认this指向创建的空对象
返回执行的结果
// 在构造函数中return Object/Number/String可以改变this指向
function Person(name, age) {
this.name = name;
this.age = age;
}
let p = new Person('bob', 30);
console.dir(p)
image.png
function Person(name, age) {
this.name = name;
this.age = age;
return 1; //"a" //null
}
let p = new Person('bob', 30);
console.dir(p)
image.png
function Person(name, age) {
this.name = name;
this.age = age;
return {}; //[] // Function
}
let p = new Person('bob', 30);
console.dir(p)
image.png
image.png
image.png