Created
November 16, 2020 11:56
-
-
Save cihat/06e1896dab46d1144fe1e8b77bebf86b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Types of Properties | |
| There are two different types of properties: data properties and accessor | |
| properties. Data properties contain a value, like the name property from earlier examples in this chapter. | |
| The default behavior of the [[Put]] method | |
| is to create a data property, and every example up to this point in the | |
| chapter has used data properties. Accessor properties don’t contain a value | |
| but instead define a function to call when the property is read (called | |
| a getter), and a function to call when the property is written to (called a | |
| setter). Accessor properties only require either a getter or a setter, though | |
| they can have both. | |
| There is a special syntax to define an accessor property using an | |
| object literal: | |
| var person1 = { | |
| _name: "Nicholas", | |
| get name() { | |
| console.log("Reading name"); | |
| return this._name; | |
| }, | |
| set name(value) { | |
| console.log("Setting name to %s", value); | |
| this._name = value; | |
| } | |
| }; | |
| console.log(person1.name); // "Reading name" then "Nicholas" | |
| person1.name = "Greg"; | |
| console.log(person1.name); // "Setting name to Greg" then "Greg" | |
| This example defines an accessor property called name. There is a data | |
| property called _name that contains the actual value for the property u. | |
| (The leading underscore is a common convention to indicate that the | |
| property is considered to be private, though in reality it is still public.) | |
| The syntax used to define the getter v and setter w for name looks a lot | |
| like a function but without the function keyword. The special keywords get | |
| and set are used before the accessor property name, followed by parentheses and a function body. | |
| Getters are expected to return a value, while | |
| setters receive the value being assigned to the property as an argument. | |
| Even though this example uses _name to store the property data, you | |
| could just as easily store the data in a variable or even in another object. | |
| This example simply adds logging to the behavior of the property; there’s | |
| usually no reason to use accessor properties if you are only storing the | |
| data in another property—just use the property itself. Accessor properties | |
| are most useful when you want the assignment of a value to trigger some | |
| sort of behavior, or when reading a value requires the calculation of the | |
| desired return value. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment