[AskJS] ways to create a javascript object?
javascript - Is creating JS object with Object.create(null) the same as {}? - Stack Overflow
Which way is best for creating an object in JavaScript? Is `var` necessary before an object property? - Stack Overflow
Which way is the best way to create objects in Javascript?
Videos
Are there any other ways of creating a javascript object than object literals, factory functions,constructor functions and class instance?
They are not equivalent. {}.constructor.prototype === Object.prototype while Object.create(null) doesn't inherit from anything and thus has no properties at all.
In other words: A JavaScript object inherits from Object by default, unless you explicitly create it with null as its prototype, like: Object.create(null).
{} would instead be equivalent to Object.create(Object.prototype).
In Chrome DevTools you can see that Object.create(null) has no prototype, while {} does.

They are definitely not equivalent. I'm writing this answer to more fully explain why it makes a difference.
var p = {};Creates an object that inherits the properties and methods from
Object.var p2 = Object.create(null);Creates an object that doesn't inherit anything.
If you are using an object as a map, and you create an object using method 1 above, then you have to be extra careful when doing lookups in the map. Because the properties and methods from Object are inherited, your code may run into a case where there are keys in the map that you never inserted. For example, if you did a lookup on toString, you would find a function, even though you never put that value there. You can work around that like this:
if (Object.prototype.hasOwnProperty.call(p, 'toString')) {
// we actually inserted a 'toString' key into p
}
Note that it is fine to assign something to p.toString, it will simply override the inherited toString function on p.
Note that you can't just do p.hasOwnProperty('toString') because you may have inserted a key "hasOwnProperty" into p, so we force it to use the implementation in Object.prototype.
On the other hand, if you use method 2 above, then you won't have to worry about things from Object appearing in the map.
You can't check for the existence of a property with a simple if like this:
// Unreliable:
if (p[someKey]) {
// ...
}
The value might be an empty string, might be false, or null, or undefined, or 0, or NaN, etc. To check whether a property exists at all, you would still need to use Object.prototype.hasOwnProperty.call(p, someKey).
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.
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.
It's really down to taste. This way:
var anotherVariable = new someObjectType({
property1: "Some value for this named property",
property2: "This is the value for property 2"
});
... is generally better if there's more than 2/3 arguments, as it aids readability and makes it easier to avoid the optional argument problem (fn(null,null,null,123')).
Another consideration is performance. Passing arguments in the conventional way will be faster, but this speed gain only becomes significant in very performance-sensitive situations.
Can I use that second way to instantiate a variable of an object type that has been defined using the "classical"way of defining the object type with that implicit constructor?
Not easily. If you want to instantiate a constructor by using a hash instead of just passing arguments, and you don't have control over the source, then you could "wrap" it:
var _constructor = SomeConstructorFunction;
SomeConstructorFunction = function(hash) {
return new _constructor(hash.property1, hash.property2);
};
I wouldn't really recommend messing with third-party APIs just for the sake of style though.
If I want to create an array of these objects, are there any other considerations?
How big is the array? What's the array for exactly? Performance might be worth considering...
Best way to create javascript objects is quit using new (at least if you subscribe to the crockford camp)
myObjectType = function(props) {
// anything defined on props will be private due to the closure
props.privateVar = "private";
// anything defined on obj will be public
obj = {};
obj.testing = new function() {
alert(props.privateVar);
};
return obj;
};
instance = myObjectType({prop1: "prop"});
// if we want inheritance, it just means starting with the base type instead of
// a new object
subType = function(props) {
obj = myObjectType(props);
obj.subTypeProperty = "hello.";
return obj;
};
Page 52 of Javascript: The Good Parts, I highly recommend it :-)