var name = "window"; var person1 = { name: "person1", show1: function() { console.log(this.name); }, show2: () => console.log(this.name), show3: function() { return function() { console.log(this.name); } }, show4: function() { return () => console.log(this.name); } }; var person2 = { name: "person2" }; person1.show1(); //person1 person1.show1.call(person2) //person2 person1.show2();//window person1.show2.call(person2); //window person1.show3()(); //window person1.show3().call(person2);//person2 person1.show3.call(person2)();//window person1.show4()();//person1 person1.show4().call(person2); //person1 person1.show4.call(person2)(); //person2
以上实例说明es6箭头函数this指向所遵循的三条原则:
- this指向函数上一层函数this,若无上一层函数,指向全局window;
- 定义函数时所在上下文中的this;
- this指向定义时所在的对象,而非使用时所在的对象。