js.info part3 – dot notation

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:

  • base is the object.
  • name is the property.
  • strict is true if use strict is 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:

  1. Call obj[Symbol.toPrimitive](hint) if the method exists,
  2. Otherwise if hint is "string"
    • try obj.toString() and obj.valueOf(), whatever exists.
  3. Otherwise if hint is "number" or "default"
    • try obj.valueOf() and obj.toString(), whatever exists.

 

let user = {
name:”John”,
money:1000,
[Symbol.toPrimitive](hint) {
console.log(`hint: ${hint}`);
returnhint==”string”?`{name: “${this.name}”}`:this.money;
}
};
// conversions demo:
console.log(user); // hint: string -> {name: “John”}
console.log(+user); // hint: number -> 1000
console.log(user + 500); // hint: default -> 1500
http://javascript.info/constructor-new

Leave a comment

Design a site like this with WordPress.com
Get started