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?
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 toarguments.0()
, you see, isn’t itarguments
that calls this function, sothis
points to it when running.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
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.
o.show()
’sthis
points too
, but it has nothing to do with this question. Thefn
identifier in
o.show()
is parsed to obtain a reference type (internal type), and itsbase
attribute (the active object whose value is theshow()
method in this question) isthis
pointing. Because the active object returnsnull
,this
points tonull
, and thus towindow
.arguments[0]()
'sarguments[0]
also returns a reference type, and the value of itsbase
attribute isarguments
, sothis
points toarguments
.