How is data passed to anonymous functions in JavaScript?

后端 未结 3 2117
萌比男神i
萌比男神i 2021-02-10 03:01

When I pass \'this\' to an anonymous function like so:

MyClass.prototype.trigger = function(){
    window.setTimeout(function(){this.onTimeout();},1000);
}
         


        
3条回答
  •  再見小時候
    2021-02-10 03:25

    What you are experiencing is the correct behavior - it's not a good behavior, but it's part of the language. The value of "this" is reset inside every function definition. There are four ways to call a function that have different ways of setting "this".

    1. The regular function invocation
      myFunc(param1, param2);
      This way of calling a function will always reset "this" to the global object. That's what's happening in your case.
    2. Calling it as a method
      myObj.myFunc(param1, param2);
      This unsurprisingly sets "this" to whatever object the method is being called on. Here, "this" == "myObj".
    3. Apply method invocation
      myFunc.apply(myObj, [param1, param2])
      This is an interesting one - here "this" is set to the object you pass as the first parameter to the apply method - it's like calling a method on an object that does not have that method (be careful that the function is written to be called this way). All functions by default have the apply method.
    4. As a constructor (with "new")
      myNewObj = new MyConstructor(param1, param2);
      When you call a function this way, "this" is initialized to a new object that inherits methods and properties from your function's prototype property. In this case, the new object would inherit from MyConstructor.prototype. In addition, if you don't return a value explicitly, "this" will be returned.

    The solution you used is the recommended solution - assign the outside value of "this" to another variable that will still be visible inside your function. The only thing I would change is to call the variable "that" as Török Gábor says - that's sort of the de-facto standard and might make your code easier to read for other programmers.

提交回复
热议问题