本文纯属自己结合网上文章总结,有问题和不同想法欢迎留言指正
/********************简单小例子********************/
????var test =function () {
???????console.log(this);
???};
???// test(); //window
/*****************************2***********************************/
???var test2 =function () {
???????console.log(this);
???????return function () {
???????????console.log(this)
???????}
???};
???var bb={
???????a:‘1‘,
???????cc:test2 //赋值类型还未执行
???};
???// bb.cc()(); // 1.obj ?2.window
???/*****************************3***********************************/
???var test3 =function () {
???????console.log(this);
???????return function () {
???????????console.log(this)
???????}
???};
???var bb3={
???????a:‘1‘,
???????cc:test3() //默认在最外层执行
???};
???bb3.cc(); // 1.window ?2.obj
???
???//test2 tes3 只是一个括号的差别,决定指向的调用者;
???/************普通函数例子*****************/
???var obj = {
???????birth: 1990,
???????getAge: function () {
???????????var b = this.birth;
???????????var that=this;
???????????console.log(this); ?//this指向obj
???????????return function () {
???????????????console.log(that);//that缓存保留在指向obj
???????????????console.log(this); ?//this指向window ?最终的调用者不是obj而是window;
???????????};
???????}
???};
???// obj.getAge()();//直接指向调用者“obj.getAge()”执行后就变成“()”而“()直接在最外层window上”
???/************箭头函数登入*****************/
???var obj2 = {
???????name:‘obj2‘,
???????birth: 1990,
???????getAge: function () {
???????????var b = this.birth; // 1990
???????????return () => {
???????????????var c=‘hehe‘;
???????????????console.log(this);//obj2
???????????????return () => {
???????????????????console.log(this) //obj2 箭头函数this始终指向最外层obj2;
???????????????}
???????????}
???????}
???};
???// obj2.getAge()()();
//结合两个例子箭头函数的设计更加合理的,this始终保持指向定义时候的obj2,传统的函数在这种情况就直接指向window,
// 个人感觉有点不合理,
/*************************普通构造函数***************************************/
function Fn(name,age){
???this.name=name;
???this.age=age;
???console.log(this); //通过new一个实例之后this指向会指向这个对象
???return function () {
???????console.log(this) ?//最终执行调用的还是window;不是new出来的对象
???};
}
???// var obj=new Fn(‘张飞‘,‘14‘); //this Fn
???// obj(); //this window
???/*******************箭头构造函数*********************************************/
???function Fn2(name,age){
???????this.name=name;
???????this.age=age;
???????console.log(this); //obj2
???????return () => {
???????????console.log(this) //obj2
???????????return () => {
???????????????console.log(this) //obj2
???????????}
???????}
???}
???// var obj2=new Fn2(‘张飞‘,‘14‘); //this指向obj2
???// obj2(); //this指向obj2
???// Fn2()()();//如果构造函数直接当做普通函数来执行,那么全部指向最初的window
???//通过对比可以发现总结一下箭头函数很好的解决了this原来在函数内部指向不合理的情况。你只要记住箭头函数会继承最初
???//最外层定义的this
js this 指向(es5)和es6箭头函数this指向问题总结(邹文丰版)
原文地址:https://www.cnblogs.com/zou1234/p/8729082.html