| A beginner's guide to Objects in JavaScript | 5/13/23 |
//object literaly syntax
const person = {
age: 100,
name: 'John',
sayHello: function (greeting = 'Hey') {
return `${greeting} ${this.name}`;
}
}
//longer notation, not used because literal is cleaner
const person = new Object ({
age: 100,
name: 'John',
});
//to access properties use dot notation or square bracket
console.log(person.age);
console.log(person['age']); //can reference property using a variable by removing ''
//method shorthand
sayHello (greeting = 'Hey') {
return `${greeting} ${this.name}`;
}const person1 = {
first: 'John',
last: 'Doe',
};
//spread operator, creates a shallow copy of the object instead of reference it
const person3 = { ...person1 };
Object.assign({}, person1); //old way to copy object{% code title="New keyword" %}
//prototype chain
function userCreator(name, score) {
//const newUser = Object.create(functionStore);
/* newUser */ this.name = name;
/* newUser */ this.score = score;
//return newUser;
};
/* functionStore */ this.prototype // {};
/* functionStore */ this.prototype.increment = function() {
this.score++;
}
//new keyword automates two things
//1. create new user object.
//2. Return the new user object
const user1 = new userCreator("Eva", 9){% endcode %}
{% code title="Class keyword" %}
//class syntactic sugar
class UserCreator {
constructor (name, score) {
this.name = name;
this.score = score;
}
increment() {this.score++;}
login() { console.log("login"); }
}
const user1 = new UserCreator("Eva", 9);
user1.increment();{% endcode %}
this
class {}
Prototypes
OO vs. OLOO
| constructor | The constructor property returns a reference to the Object constructor function that created the instance object. Note that the value of this property is a reference to the function itself, not a string containing the function's name. The value is only read-only for primitive values such as 1, true and "test". |
| enumerable | Enumerable Properties in JavaScript. Enumerable properties are properties whose internal enumerable flag set to true. Enumerable simply means "countable", and with JavaScript objects, enumerable properties are those we are typically interested in when iterating over properties. |
| Instance | An object created by a constructor is an instance of that constructor. In object-oriented programming (OOP), an instance is a concrete occurrence of any object, existing usually during the runtime of a computer program. |
| polymorphism | Polymorphism is the presentation of one interface for multiple data types. |
| properties | JavaScript Properties. Properties are the values associated with a JavaScript object. A JavaScript object is a collection of unordered properties. Properties can usually be changed, added, and deleted, but some are read only. |
| .fromEntries() | The Object.fromEntries() method transforms a list of key-value pairs into an object. |
| onclick | |
| .scrollTo() | |
| .setInterval() | |
| .setTimeout() |
