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 (显示绑定person2,显示绑定优先级高于person1.foo1的隐式绑定)

person1.foo2() // person1  (上层作用域中的this是person1函数)
person1.foo2.call(person2) // person1 (显示绑定在箭头函数中无效,所以结果还是上层作用域中的this是person1函数)

person1.foo3()() // window (person1.foo3()得到返回函数 加小括号进行直接调用 this指向全局作用域window)
person1.foo3.call(person2)() // window (person1.foo3.call(person2)得到返回函数后,独立函数调用指向全局)
person1.foo3().call(person2) // person2 (person1.foo3()得到返回函数后,显示绑定person2)

person1.foo4()() // person1 (箭头函数中没有this,向上一层作用域找 this指向person1)
person1.foo4.call(person2)() // person2 (person1.foo4.call(person2)显示绑定person2,得到返回的箭头函数后,向上一层作用域找,this指向person2)
person1.foo4().call(person2) // person1 (person1.foo4()得到返回箭头函数显示绑定person2无效,向上一层作用域找,this指向person1)


External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.