Function defined with 'this', but executing without 'this'

后端 未结 3 411
滥情空心
滥情空心 2020-12-19 16:07

I was expecting the 2nd call of the \"taco\" function to generate a runtime error since I am not calling it with the \"this\" keyword:

function foo() {
    v         


        
3条回答
  •  不思量自难忘°
    2020-12-19 16:24

    The reason is this in foo(), when it's called just as is, will reference a global object. This means taco function will be introduced in the global scope.

    To get the functionality you want use new foo() syntax instead. Then this will refer to a new object, which taco property will be assigned a new value (function). Calling taco directly will get you an error then.

提交回复
热议问题