xxxxxxxxxx
//object constructor with a method
function person(name,age){
this.name=name;
this.age=age;
this.setName= function(name){
this.mame=name;
}
}
const p1 = new person();
p1.setName("John");
xxxxxxxxxx
var student = { // object name
firstName:"Jane", // list of properties and values
lastName:"Doe",
age:18,
height:170,
fullName : function() { // object function
return this.firstName + " " + this.lastName;
}
};
xxxxxxxxxx
class ObjectLayout {
constructor() {
this.firstName = "Larry"; //property
}
sayHi() { // Method
return `Hello from ${this.firstName}`;
}
}
const object = new ObjectLayout();
// object.firstName is Larry;
// object.sayHi() gives "Hello from Larry"
xxxxxxxxxx
// Method 1: Object literal
const objLiteral = {
key1: value1,
key2: value2,
};
// Method 2: Constructor function
function ObjConstructor(key1, key2) {
this.key1 = key1;
this.key2 = key2;
}
const objConstructor = new ObjConstructor(value1, value2);
// Method 3: Object.create()
const objProto = {
key1: value1,
key2: value2,
};
const objCreate = Object.create(objProto);
// Method 4: ES6 class (syntactic sugar over constructor function)
class ObjClass {
constructor(key1, key2) {
this.key1 = key1;
this.key2 = key2;
}
}
const objClass = new ObjClass(value1, value2);
xxxxxxxxxx
const person = {
name: 'Anthony',
age: 32,
city: 'Los Angeles',
occupation: 'Software Developer',
skills: ['React','JavaScript','HTML','CSS']
}
//Use Template Literal to also log a message to the console
const message = `Hi, I'm ${person.name}. I am ${person.age} years old. I live in ${person.city}. I am a ${person.occupation}.`;
console.log(message);
xxxxxxxxxx
var myObject = {}; // Empty object
// Object with properties
var person = {
name: "John Doe",
age: 30,
occupation: "Developer"
};
console.log(person.name); // Output: "John Doe"
console.log(person.age); // Output: 30
console.log(person.occupation); // Output: "Developer"
xxxxxxxxxx
Objects are the collection of properties which contain values as key:value pairs.
A property is also like a variable which stores data, but in property we stores
data in key:value pair i.e, age:21
We access property of an objects by object_name.property_name
xxxxxxxxxx
let myDog = {
legs: value
}
console.log(myDog);
/*Doesn't have to be a Dog it can be anyting you want*/