We all know Javascript objects. An object is nothing more than a container holding key-value pairs.
However, there’s a lot more to Javascript objects. Let’s go over some key concepts.
1. Defining properties with expressions
JS objects can be defined with expressions as property values. These expressions are immediately computed and stored as values.
Example:
let obj = { num: (1 + 2) * 3 }
In this case, the value of num is stored as 9 after the expression is evaluated.
let obj = { num: 9 }
But what if you want to define a property with a lazily computed expression?
The only way to achieve that is by wrapping the expression in a function.
function calc() { return (1 + 2) * 3; } let obj = { num: calc }
Now, obj.num holds a reference to the function calc. The value will only be computed by calling obj.num() when necessary.
2. Types of property names
Property names can be of any type but automatically converted to strings.
let obj = { "12": "this is a string name", // string, both obj[12] and obj["12"] will work 14: "this is an integer name", // coerced to a string, both obj[14] and obj["14"] will work true: "this is a boolean prop name", // coerced to a string, both obj[true] and obj["true"] will work [newObj]: "this is an obj prop name" // coerced to a string, obj[newObj] will not work but obj["newObj"]
3. Concise object methods
Starting from ES6, Javascript allows concise object method definitions without needing the “function” keyword.
let obj = { hello(){ console.log("Hello"); } }
In this example, the object has a method called “hello” which can be called by obj.hello().
We will see more in the upcoming episodes.
1 Comment
Поиск в гугле