There is no best way, it depends on your use case.
- Use way 1 if you want to create several similar objects. In your example,
Person(you should start the name with a capital letter) is called the constructor function. This is similar to classes in other OO languages. - Use way 2 if you only need one object of a kind (like a singleton). If you want this object to inherit from another one, then you have to use a constructor function though.
- Use way 3 if you want to initialize properties of the object depending on other properties of it or if you have dynamic property names.
Update: As requested examples for the third way.
Dependent properties:
The following does not work as this does not refer to book. There is no way to initialize a property with values of other properties in a object literal:
var book = {
price: somePrice * discount,
pages: 500,
pricePerPage: this.price / this.pages
};
instead, you could do:
var book = {
price: somePrice * discount,
pages: 500
};
book.pricePerPage = book.price / book.pages;
// or book['pricePerPage'] = book.price / book.pages;
Dynamic property names:
If the property name is stored in some variable or created through some expression, then you have to use bracket notation:
var name = 'propertyName';
// the property will be `name`, not `propertyName`
var obj = {
name: 42
};
// same here
obj.name = 42;
// this works, it will set `propertyName`
obj[name] = 42;
Answer from Felix Kling on Stack OverflowWhich way is best for creating an object in JavaScript? Is `var` necessary before an object property? - Stack Overflow
ecmascript 5 - Is there any reason to use Object.create() or new in JavaScript? - Stack Overflow
Understanding Object.create() in JavaScript
Which way is the best way to create objects in Javascript?
There is no best way, it depends on your use case.
- Use way 1 if you want to create several similar objects. In your example,
Person(you should start the name with a capital letter) is called the constructor function. This is similar to classes in other OO languages. - Use way 2 if you only need one object of a kind (like a singleton). If you want this object to inherit from another one, then you have to use a constructor function though.
- Use way 3 if you want to initialize properties of the object depending on other properties of it or if you have dynamic property names.
Update: As requested examples for the third way.
Dependent properties:
The following does not work as this does not refer to book. There is no way to initialize a property with values of other properties in a object literal:
var book = {
price: somePrice * discount,
pages: 500,
pricePerPage: this.price / this.pages
};
instead, you could do:
var book = {
price: somePrice * discount,
pages: 500
};
book.pricePerPage = book.price / book.pages;
// or book['pricePerPage'] = book.price / book.pages;
Dynamic property names:
If the property name is stored in some variable or created through some expression, then you have to use bracket notation:
var name = 'propertyName';
// the property will be `name`, not `propertyName`
var obj = {
name: 42
};
// same here
obj.name = 42;
// this works, it will set `propertyName`
obj[name] = 42;
There is various way to define a function. It is totally based upon your requirement. Below are the few styles :-
- Object Constructor
- Literal constructor
- Function Based
- Protoype Based
- Function and Prototype Based
- Singleton Based
Examples:
- Object constructor
var person = new Object();
person.name = "Anand",
person.getName = function(){
return this.name ;
};
- Literal constructor
var person = {
name : "Anand",
getName : function (){
return this.name
}
}
- function Constructor
function Person(name){
this.name = name
this.getName = function(){
return this.name
}
}
- Prototype
function Person(){};
Person.prototype.name = "Anand";
- Function/Prototype combination
function Person(name){
this.name = name;
}
Person.prototype.getName = function(){
return this.name
}
- Singleton
var person = new function(){
this.name = "Anand"
}
You can try it on console, if you have any confusion.
So far, if you want to create an object, you can only use literals:
var obj = {};
or the Object constructor.
var obj = Object();
But none of these methods let you specify the prototype of the created object.
This is what you can do with Object.create now. It lets you create a new object and sets the first argument as prototype of the new object. In addition, it allows you to set properties of the new object provided as second argument.
It is similar to doing something like this (without the second argument):
function create(proto) {
var Constr = function(){};
Constr.prototype = proto;
return new Constr();
}
So if you are using a construct similar to this, this when you wanted to use Object.create.
It is not a replacement for new. It is more an addition to make creating single objects which should inherit from another object simpler.
Example:
I have an object a:
var a = {
someFunction: function() {}
};
and I want b to extend this object. Then you can use Object.create:
b = Object.create(a);
b.someOtherFunction = function(){};
Whenever you have a constructor function, but you only instantiate one object from it, you might be able to replace this with Object.create.
There is general rule that applies. It depends very much on what the constructor function is doing and how you inherit from other objects, etc.
As already mentioned, Object.create() is commonly used when you want an easy way to set the prototype of a new object. What the other answers fail to mention though, is that constructor functions (which require new) are not all that different from any other function.
In fact, any function can return an object, and it's common in JavaScript to see factory functions (like constructors, but they don't require new, or use this to refer to the new object). Factory functions often use Object.create() to set the prototype of the new object.
var barPrototype = {
open: function open() { /* ... */ },
close: function close() { /* ... */ },
};
function createBar() {
return Object.create(barPrototype);
}
var bar = createBar();
Hi All,
The Odin Project has an example using an empty Student constructor, and an Eighth Grader constructor:
function Student() {
}
Student.prototype.sayName = function() {
console.log(this.name)
}
function EighthGrader(name) {
this.name = name
this.grade = 8
}
EighthGrader.prototype = Object.create(Student.prototype)
const carl = new EighthGrader("carl")
carl.sayName() // console.logs "carl"
carl.grade // 8This makes sense to me--the EighthGrader prototype is set to an object that is equal to the Student prototype, giving EighthGrader objects access to the Student.prototype methods. However, there's nothing in the student constructor, so I tried to mess around a bit, add a parameter to the student constructor, and make a new NinthGrader object that could access those properties. It's not working as I expected:
function Student(gender) {
this.gender = gender;
}
Student.prototype.sayName = function() {
console.log(this.name)
}
function EighthGrader(name) {
this.name = name
this.grade = 8
}
function NinthGrader() {
}
EighthGrader.prototype = Object.create(Student.prototype)
NinthGrader.prototype = Object.create(Student);
const carl = new EighthGrader("carl")
carl.sayName() // console.logs "carl"
const john = new NinthGrader("male");
console.log(john.gender); // logs undefined, shouldn't it log male, since NinthGrader's prototype is Student?As I said in the comment there, I expected Student to be the prototype of of NinthGrader, which I thought would give NinthGrader objects access to the student properties (in this case, gender). Clearly I'm mistaken. Can anyone help me understand? Thanks!
Dear all,
I am trying to figure out Javascript syntax for creating objects, and it is confusing me a little bit, because there seem to be multiple ways of doing it.
I've seen:
(1)
function book(title, author){
this.title = title;
this.author = author;
}
var somebook = new book("Harry Potter", "J.K. Rowling");I've also seen the new ECMAscript 6 "class" identifier.
I've also seen:
(2)
var book = {
title: "Harry Potter", author: "J.K. Rowling"
}Is it recommended to write out a constructor function, like in (1)?
If we simply create a particular object directly, like (2), would subsequent instantiations of book objects work if we give it a different set of properties?
What is the best way to think about objects in Javascript? Thanks.