3 ms·
> there's nothing special about "this" or "self" It is special in that when a method executes say in JavaScript, the 'this' has a very specific value even thou
by galaxyLogic 3y ago
> there's nothing special about "this" or "self"
It is special in that when a method executes say in JavaScript, the 'this' has a very specific value even though you did not pass in an argument of that name nor did you ever assign a value to a local variable of that name. Depending on the language you use trying to assign to the (pseudo-) variable 'this' may or may not cause an error.
The "automatic" value 'this' has makes it special, different from other variables and arguments. That automatic value ties the method-call-syntax into the semantics of what it means to call a method as opposed to calling a free function.
This can be exemplified in JavaScript easily:
let funk = myOb.funk;
let v = myOb.funk();
let v2 = funk(); // throws error
In this case the error gets thrown if
myOb.funk internally refers to 'this'
and tries to access some field of it.
That causes an error because 'this' is
undefined inside 'funk' when it is called
as a plain function.
When you call myOb.funk() there is NO error
in the same case, because 'this' is then
NOT undefined, its value is 'myOb'.
You can access any field of myOb inside
the code of myOb.funk when you call it as
myOb.funk().
That is a big semantic difference, not
just "syntactic sugar".
- munificent 3y ago> the 'this' has a very specific value even though you did not pass in an argument of that name nor did you ever assign a value to a local variable of that name. It's just an implicit parameter named `this` whose argument happens to appear to the left of the `.` instead of after the `(`. Yes, there's a little extra work in the language to support this, but it's not particularly complex or deep semantically. (In fact `this` is particularly semantically shallow in JavaScript because as your example notes, it's not even bound when a reference to a method is taken. In most other languages, `myOb.funk` will give you a function that partially applies `this`.)