javascript - A question about this
给我你的怀抱
给我你的怀抱 2017-07-05 11:06:26
0
6
910

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

给我你的怀抱
给我你的怀抱

reply all(6)
女神的闺蜜爱上我

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.

小葫芦

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

滿天的星座

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

刘奇

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.

曾经蜡笔没有小新

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...

阿神

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template