JeffLearnsReact – Objects
Warning: count(): Parameter must be an array or an object that implements Countable in /nfs/c03/h06/mnt/47997/domains/jeffschram.com/html/wp-content/plugins/workbox-video-from-vimeo-youtube-plugin/workbox_video.php on line 192
OBJECTS JavaScript objects are containers that can store data and functions. The data we store in an object is not ordered — we can only access it by calling its associated key. const myObj = { thing: ‘value’, another: 2 } Can be accessed w dot notation myObj.thing; // ‘value’ Or bracket notation myObj[‘thing’]; // […]
Warning: count(): Parameter must be an array or an object that implements Countable in /nfs/c03/h06/mnt/47997/domains/jeffschram.com/html/wp-content/plugins/workbox-video-from-vimeo-youtube-plugin/workbox_video.php on line 192
OBJECTS
JavaScript objects are containers that can store data and functions. The data we store in an object is not ordered — we can only access it by calling its associated key.
const myObj = {
thing: ‘value’,
another: 2
}
Can be accessed w dot notation
myObj.thing; // ‘value’
Or bracket notation
myObj[‘thing’]; // ‘value’
You can assign variables to keys.
let keyVar = ‘another’;
myObj[keyVar]; // 2
You can only do this with bracket notation.
Objects are considered mutable, which means you can change them after they’re created. Even if you save an object to a const variable, you can still add to and edit the key-value pairs inside of it without causing an error.
You can add to objects like this:
myObj.newThing = ‘yo’;
myObj[‘newThing’] = ‘yo’;
Edit objects like this
myObj.newThing = ‘foo’;
myObj[‘newThing’] = ‘foo’;
The value of a key can be a FUNCTION. These are called METHODS.
myObj = {
foo: ‘bar’,
baz: ‘blah’,
doSomething: () => {
// the function stuff here
}
}
Then the function is called like this:
myObj.doSomething();
Defining METHODS can be simplified in ES6
myObj = {
foo: ‘bar’,
baz: ‘blah’,
doSomething() {
// the function stuff here
}
}
You need ‘this’ in objects.
In Javascript, ‘this’ refers to the object we call it inside.
myObj = {
foo: ‘bar’,
baz: ‘blah’,
doSomething() {
// the function stuff here
if (this.baz === ‘blah’) {
// can only access baz if this.baz is used
}
}
}
Getters and Setters I
A common object design paradigm is to include getter and setter methods as attributes.
Getter and setter methods get and set the properties inside of an object. There are a couple of advantages to using these methods for getting and setting properties directly:
You can check if new data is valid before setting a property.
You can perform an action on the data while you are getting or setting a property.
You can control which properties can be set and retrieved.
myObj = {
_foo: ‘bar’,
_baz: ‘blah’,
doSomething() {
// the function stuff here
if (this.baz === ‘blah’) {
// can only access baz if this.baz is used
}
}
}
Powered by WPeMatico