im new to javascript. i have a simple question here.
i see below code snipet:
var self = this;
.....
self.push = function () {
var args = [].concat.apply([], arguments);
args.forEach(self.write);
return self;
};
self.write is another function.
q1: why set self = this.
q2: why we can not write the push function as simple as arguments.forEach(self.write);
q1: why set self = this.
That is used when an inner function wants to keep a reference to an outer function's this
in a closure. The value of this
is set by how a function is called, so the inner function has its own this
that "shaddows" the outer function's this
.
q2: why we can not write the push function as simple as arguments.forEach(self.write);
Becaue the arguments object is not an array so doesn't have a forEach
method. The line:
var args = [].concat.apply([], arguments);
creates an array with members from the arguments object. It could also do:
[].forEach.call(arguments, ...)
or (preferred by many):
Array.prototype.forEach.call(arguments, ...);
A point raised by Jack is that it seems as if this
in the function is self
anyway. But this
is set by the call, not by how the function is assigned or created (ignoring ES5 bind) so you can't tell what the function's this
will be until you see the call. You haven't posted that so we don't know. e.g.
self.push = function () {
...
}
Here, if the function is called as self.push()
then its this
is set to self
anyway. However, if its this
is set to something else, e.g.
var pushAlias = self.push;
...
pushAlias();
Here self.push
is called without its this
being set, so it will default to the global/window object (or undefined in strict mode). Using self
within the function means that that doens't matter, the function still has a reference to the outer this
at the time it was assigned to the push
method.
Q1 In Javascript, "this" can be different things at different times, by making self "this" it means that the "this" at the time of that assignment will always be the this used.
Q2 arguments looks a little like an array but it's not, so first it creates an array so array functions can be called on it.