本人学习过程中编写,定有不足之处,如果有错误,请您积极指正;如果有帮助,请不要吝啬您的赞美(点赞),欢迎各位大佬点赞评论。
es5中this指代
function Animal(){
this.name = '花花';
this.test = {
name : '亮亮',
getname : function () {
console.log(this.name);
}
}
}
let animal = new Animal();
animal.test.getname(); //亮亮
在es5中this指向的该函数被调用的对象,哪个对象调用了这个函数,this就指向谁。
es6中this指代
function Animal(){
this.name = '花花';
this.test = {
name : '亮亮',
getname : () =>{
console.log(this.name);
}
}
}
let animal = new Animal();
animal.test.getname(); //花花
在es6中,this指向的是定义时this的指向,换句话说,就是,在其函数调用之前,创建实例的时候this就已经被绑定了;例子中在Animal函数定义时,this指向的是Animal函数体中的this。而es5正好相反,es5中在函数调用之前没有绑定this,而是在调用时绑定this。
接下来我们分析稍微复杂一些的案例:
var name = '亮亮';
function Animal(){
this.name = '花花';
console.log(this);
let b = function(){
console.log(this.name);
console.log(this);
}
b();
}
new Animal();
当new Animal()执行时,是window调用的b(),所以b中的this指向的是window;
var name = '亮亮';
function Animal(){
this.name = '花花';
console.log(this);
let b = function(){
console.log(this.name);
console.log(this);
}
b();
}
Animal();
当调用Animal()时我们会发现两种截然不同的情况,因为此时,我们并没有实例化对象,执行Animal时,this.name中的this指向的是window,改写了var name = ‘亮亮’。此语句执行就好比于:
var name = '亮亮';
this.name = '花花';
console.log(this);
let b = function(){
console.log(this.name);
console.log(this);
}
b();
var name = '亮亮';
function Animal(){
this.name = '花花';
console.log(this);
let b = ()=>{
console.log(this.name);
console.log(this);
}
b();
}
new Animal(); //花花
Animal(); //花花
new Animal()时,this指向实例化对象;
Animal()时,this指向window;