Cases where 'this' is the global Object in Javascript

前端 未结 4 1218
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-30 11:37

I\'m playing around with different ways to call a function that is an attribute of an Object in Javascript and looking at which type of calls set \'this\' to be the Object a

4条回答
  •  春和景丽
    2020-11-30 12:22

    The difference between the first three cases and the last two cases is that you're storing the bar function in a variable. Functions don't "know" that they're properties of an object. So in the last two cases, you're just calling regular functions.

    In last two cases, you could make "this" refer to "foo" by using Function.call or function.apply

    f.call(foo)
    

    Call and apply allow you to control what "this" refers to inside the function you're calling.

    While functions don't know whether they're attached to an object or not, they do know what scope they're declared in. There's lots of useful stuff you can do based on that. In the last example, you're creating a new scope by doing (f = foo.bar)(), but it has no effect whatsoever.

提交回复
热议问题