两点注意:
1.function做为返回值再调用时,属于在全局执行,所以this应指向全局
2.箭头函数没有this,故直接向外层找,且因为没有this,所以无法绑定this
第一题:
var name = 'window' function Person (name) { this.name = name this.foo1 = function () { console.log(this.name) } this.foo2 = () => console.log(this.name) this.foo3 = function () { return function () { console.log(this.name) } } this.foo4 = function () { return () => { console.log(this.name) } } } var person1 = new Person('person1') var person2 = new Person('person2') person1.foo1() // person1 person1.foo1.call(person2) // person2 person1.foo2() // person1 person1.foo2.call(person2) // person1 person1.foo3()() // window person1.foo3.call(person2)() // window person1.foo3().call(person2) // person2 person1.foo4()() // person1 person1.foo4.call(person2)() // person2 person1.foo4().call(person2) // person1
第二题:
var name = 'window' function Person (name) { this.name = name this.obj = { name: 'obj', foo1: function () { return function () { console.log(this.name) } }, foo2: function () { return () => { console.log(this.name) } } } } var person1 = new Person('person1') var person2 = new Person('person2') person1.obj.foo1()() // window person1.obj.foo1.call(person2)() // window person1.obj.foo1().call(person2) // person2 person1.obj.foo2()() // obj person1.obj.foo2.call(person2)() // person2 person1.obj.foo2().call(person2) //obj
标签:function,obj,name,person2,person1,call,两道,指针 From: https://www.cnblogs.com/xt112233/p/16994649.html