简体   繁体   中英

Javascript object creation using literals vs custom constructor functions

I understand that there are multiple ways to create an object in javascript and I have been reading that object literal syntax is generally preferred. (Correct?)

What I haven't been able to figure out is if there is ever a reason to use any of the other ways to create objects, such as a custom constructor function ( var p = new Person("Adam") )? Is it true to use a custom constructor function only if I want private variables or to add methods or properties to its prototype? Is there no way to do these in a literal?

The discussion usually is about to prefer

var myObject = {};

over

var myObject = new Object();

If you however create your own constructor functions you are perfectly allowed to instantiate them with the new keyword, nothing controversial there.

You can use the custom constructor function when you want to create instances of objects, similar to Java.

For example:

function MyObj(x){
   this.x = x;
}

MyObj.prototype.printX = function(){
   alert(this.x);
}

var obj1 = new MyObj("hello");
var obj2 = new MyObj("hello2");
obj1.printX();//prints hello
obj2.printX();//prints hello2

Now I have two instances of this object. If I used String literals I would need to clone the object into a new var in order to get another instance.

The preferred method would be to use JSON: var p = { "name":"Adam" };

If you have a lot of member variables you need to initialize, or will be using a lot of objects (such as an array of them), etc. then it only makes sense to go ahead and create a function (constructor) which will do all of this for you. Unless you want your code to look like this:

var a = { "name":"Adam", "age":23, "city":"Boston" };
var b = { "name":"Jeff", "age":24, "city":"San mateo" };
var c = { "name":"Aaliyah", "age":25, "city":"New York" };
var d = { "name":"Mary", "age":26, "city":"Dallas" };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM