Why can I do this:
Array.prototype.foo = function() {
this.splice(0, this.length);
return this.concat([1,2,3]);
}
But I can’t do this:
Array.prototype.foo = function() {
return this = [1,2,3];
}
Both functions destroy the value of this and change it to [1,2,3] but the second one throws the following error: Uncaught ReferenceError: Invalid left-hand side in assignment
I suspect it’s because allowing assignment means I could potentially change the array to something else (like a string), but I’m hoping someone out there knows for sure and/or has a more detailed explanation.
It’s not permitted to assign a value to
thiswithin a function. Suppose that you could do this, and your code looked something like:Now, what if you did this:
The act of calling a function
.foo()on an object should not change the identity of the object. This would be very confusing for the caller ifbsuddenly started referring to a different object thanasimply because some method was called.