In JavaScript, there are three ways to create your own objects. Taking into account that almost everything in JS It’s an object.
Object literals
The simplest way to create an object in JS it’s through curly brackets { }
.
Define and create a single object in one statement
const person = {
name : 'Freddy',
sayHello() {
return `Hi ${this.name}`
}
};
console.log(person.sayHello()) // Hi Freddy
New operator
Using the new operator is the same thing as creating objects literally. It’s recommended to use object literals, instead of this, for simplicity and execution speed.
const person = new Object()
person.name = 'Freddy'
person.sayHello = () => {
return `Hi ${this.name}`
}
console.log(person.sayHello()) // Hi Freddy
Also, you can create an object through a constructor function. In this case, the new operator returns an instance of the function, if the function has not an explicit return statement it’ll “this “
function Person (name) {
this.name = name
this.sayHello = function() {
return `Hi ${this.name}`
}
}
const person = new Person('Freddy')
console.log(person.sayHello()) // Hi Freddy
Object.create() method
In order to define and create a new object through the create
method, we have to use the prototype from another one.
const person = Object.create(Object.prototype)
person.name = 'Freddy'
person.sayHello = function sayHello() {
return `Hi ${this.name}`
}
console.log(person.sayHello()) // Hi Freddy
Top comments (4)
You're right, thank you!
class Person {
constructor(name){
this.name = name
};
sayHello(){
return
Hi ${this.name}
}
}
const person = new Person('Jon Doe');
console.log(person.sayHello()); //HI Jon Doe
You can also use the constructor function to create an object in es6.
Yeah... that's it, thank you