kayut
05-28-2018, 03:56 PM
Hey,
There are 3 different ways to create a new object:
let myObject = {};
var myObject = {
name: “Engage",
days: 30
}
var myObject = new Object();
Now my question is about the 2 different ways of instantiating a new object.
You can either use an existing object as prototype of your new object, like this:
var person = {
name: "David",
age: 20,
};
// Create theDude object and use person object as its prototype
var theDude = Object.create(person);
Or you can use a Constructor function to create your new object like this:
function Person (name) {
this.name = name;
this.age = 20;
this.getInfo = function getInfo() {
return this.name + ' is ' + this.age + ' years old.';
};
}
// Instantiating a new object using the new keyword and a constructor function
var theDude = new Person("David");
My question is:
What is the difference between the last 2 methods of instantiating a new object?
Which method is more recommended?
In the real world, which one is used more?
Thanks
There are 3 different ways to create a new object:
let myObject = {};
var myObject = {
name: “Engage",
days: 30
}
var myObject = new Object();
Now my question is about the 2 different ways of instantiating a new object.
You can either use an existing object as prototype of your new object, like this:
var person = {
name: "David",
age: 20,
};
// Create theDude object and use person object as its prototype
var theDude = Object.create(person);
Or you can use a Constructor function to create your new object like this:
function Person (name) {
this.name = name;
this.age = 20;
this.getInfo = function getInfo() {
return this.name + ' is ' + this.age + ' years old.';
};
}
// Instantiating a new object using the new keyword and a constructor function
var theDude = new Person("David");
My question is:
What is the difference between the last 2 methods of instantiating a new object?
Which method is more recommended?
In the real world, which one is used more?
Thanks