var length = 10;
function cl() {
console.log(this.length);
}
var o = {
length: 20,
show: function (fn) {
fn();
arguments[0]();
}
}
o.show(cl); // 10
Regarding this question, I want to know whether this in js points to whoever calls it? Why does this in cl still point to window instead of o object when called for the first time? I know it’s probably wrong if I don’t use call
, but why is it wrong?
Why does the second one point to arguments?
At the same time, why does the first output of this code when running in nodejs is undiffed?
巴扎黑2017-07-05 10:39:50
Call directly using the function name. No matter how many layers you wrap it in, the caller is window
.
Because the square bracket operator, as an object value operation, can be equal to the point .
operator in a sense, so the form here can actually be analogized to arguments.0()
, you see, isn’t it arguments
that calls this function, so this
points to it when running.
欧阳克2017-07-05 10:39:50
The point of this is not determined when it is declared but is defined when it is called. There are several situations
Ordinary function call, this is the global object or undefined
As a method of an object, this is that object
new expression, this is the newly created object prototyped with this function
Use apply/call to specify this
Use bind to fix this
This in the event handling function is the current DOM element that triggers the event (event.currentTarget)
I don’t know if it will help you
扔个三星炸死你2017-07-05 10:39:50
As far as this question is concerned.
o.show() is executed, then this used in the show function scope points to o.
But in fact, fn() is called inside, fn is not called by o, there is no o.fn... A relatively low principle is that whoever is in front of the function call point will be this in the function. This must be the default window.
arguments[0] ==> arguments.0
Arrays are also objects, and [] calls are the same as ., so this is arguments
Regarding node, because it is modular, this points to global, and when var is declared, there is no window call like in the browser. There is no such mechanism in node.
我想大声告诉你2017-07-05 10:39:50
o.show()
’s this
points to o
, but it has nothing to do with this question. The
fn identifier in
o.show()
is parsed to obtain a reference type (internal type), and its base
attribute (the active object whose value is the show()
method in this question) is this
pointing. Because the active object returns null
, this
points to null
, and thus to window
. arguments[0]()
's arguments[0]
also returns a reference type, and the value of its base
attribute is arguments
, so this
points to arguments
.