How dot notation works:
To make user.hi() calls work, JavaScript uses a trick – the dot '.' returns not a function, but a value of the special Reference Type.
The Reference Type is a “specification type”. We can’t explicitly use it, but it is used internally by the language.
The value of Reference Type is a three-value combination (base, name, strict), where:
baseis the object.nameis the property.strictis true ifuse strictis in effect.
The result of a property access user.hi is not a function, but a value of Reference Type. For user.hi in strict mode it is:
// Reference Type value (user, "hi", true)
When parentheses () are called on the Reference Type, they receive the full information about the object and its method, and can set the right this (=user in this case).
Any other operation like assignment hi = user.hi discards the reference type as a whole, takes the value of user.hi (a function) and passes it on. So any further operation “loses” this.
So, as the result, the value of this is only passed the right way if the function is called directly using a dot obj.method() or square brackets obj['method']() syntax (they do the same here). Later in this tutorial, we will learn various ways to solve this problem such as func.bind().
Date objects can be added/ subtracted
ToPrimitive to coerces objects into preferred types:
To do the conversion, JavaScript tries to find and call three object methods:
- Call
obj[Symbol.toPrimitive](hint)if the method exists, - Otherwise if hint is
"string"- try
obj.toString()andobj.valueOf(), whatever exists.
- try
- Otherwise if hint is
"number"or"default"- try
obj.valueOf()andobj.toString(), whatever exists.
- try