function MyArray() {
var self = this.arguments; //<---
this.toString = function() {
return self;
};
}
var c = new MyArray(2, 3, 1, '232');
console.log(c.toString());
undefined
function MyArray() {
var self = arguments; //<---
this.toString = function() {
return self;
};
}
var c = new MyArray(2, 3, 1, '232');
console.log(c.toString());
[2,3,1,’232′]
So, why is that so? What is the difference between this.arguments and arguments?
In JS,
thisrepresents “calling context”, which can be set a number of different ways. It has really nothing to do with variable scope. They’re entirely separate concepts. That’s whyargumentsis available as a variable, but not a property ofthis.The value of
thisvaries based on how a function is called.Called as a method
For example, if I do…
…then
thiswill refer tomy_objbecause the functionmyMethodwas called from the context ofmy_obj.Called independently as a function
but if I do…
Even though
my_objandmyMethodare the same code as the first example, the value of this will usually change to theglobalobject.Called using
.callor.applyThere are several other ways
thiscan be set as well.Using
.callor.apply, the first argument passed becomes the value ofthis. The difference between the two is how the rest of the arguments are passed.Created using
.bindThere’s also
.bind()which takes arguments in the same manner as.call(), but creates and returns a new function with thethisvalue and any other arguments permanently set.Called using the
newoperatorThe final way is when you call a function as a constructor. To do this, you use the
newoperator.In both cases, the value of
thiswill be a new object being constructed. YOu should never usenewunless the function called has been set up to be used as a constructor.