两道this指针题

两点注意:

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

 

posted @ 2022-12-20 17:03  邢韬  阅读(22)  评论(0编辑  收藏  举报