Home  >  Q&A  >  body text

javascript - A question about this

As shown in the picture, I would like to ask everyone, why is the first parameter of foo.call() window?

给我你的怀抱给我你的怀抱2663 days ago885

reply all(6)I'll reply

  • 女神的闺蜜爱上我

    女神的闺蜜爱上我2017-07-05 11:08:26

    In fact, the key to the problem is that we don’t understand the role of the call/apply function. In official terms, it means changing the scope context, but here the local context is changed to window. In fact, call/apply is a method of "killing someone with a borrowed knife", that is, if you don't have a certain attribute or method, and then you want to call the attributes or methods of other objects, it is also an implementation method of object inheritance.

    reply
    0
  • 高洛峰

    高洛峰2017-07-05 11:08:26

    In fact, it doesn’t have to be Windows, and it is better to use call. You only need to declare var that=this in f and write this of the closure function as that. This is because the closure function cannot directly obtain the environment variables of the upper function. You can only get windous, so the statement is ok. If you don’t understand, you can ask me

    reply
    0
  • 滿天的星座

    滿天的星座2017-07-05 11:08:26

    If it is a front-end, the function has an invisible parameter this, which by default points to the global variable window.
    Unless you change the object this points to, such as foo.call (other objects)
    The original sentence uses the default this parameter
    The annotation clearly states that this points to window

    I’ll write a few more sentences, otherwise I’ll make it clear

    var foo = function () {
      console.log(this.x);
    }
    foo();为什么this指向window呢
    

    In addition, the semantics of this is to point to the object that calls this function.
    Each function requires an object to call
    obj.f() means that f is called by obj
    If the front-end does not specify the calling object, the default is the global variable window to call the function

    reply
    0
  • 怪我咯

    怪我咯2017-07-05 11:08:26

    When

    javascript is designed, it will bind this in the internal function (i.e. the function in the function body) to the global object (i.e. window). I think the comment here says foo.call(window) should just be used js language to explain why this.x in foo() will output 10.

    reply
    0
  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-07-05 11:08:26

    It doesn’t say that the first parameter of foo.call must be window. The main point of the question is to understand what call is.

    https://developer.mozilla.org...

    reply
    0
  • 阿神

    阿神2017-07-05 11:08:26

    You can understand the functions and differences of call, apply, and bind

    reply
    0
  • Cancelreply