What's the point of “var t = Object(this)” in the official implementation of forEach?

后端 未结 3 1389
一个人的身影
一个人的身影 2021-01-31 06:05

According to the MDC, the ECMA-262, 5th edition gives the implementation of forEach as:

if (!Array.prototype.forEach)
{
  Array.prototype.forEach = function(fun          


        
3条回答
  •  北恋
    北恋 (楼主)
    2021-01-31 06:28

    I write var t = this; all the time. I find that the scope of this is sometimes browser-dependent; in any case it's not always clear what a browser is going to do with the keyword this as scope changes, especially in method closures. I like to dumb down my JS code to a kindergarten level to leave minimal room for individual browsers to do wonky things.

    To ensure that I'm always dealing with the this I want to be dealing with when passing this to a method or something, I always write var t = this; as the first line of my method. Then, t is a variable and obeys predictable variable scope rules, and its pointer is assigned at assignment time to the object denoted by this at that time. This way I don't have to worry about a method, other object, or noncompliant browser reinterpreting what this refers to in scope.

提交回复
热议问题