简体   繁体   English

使用文字和自定义构造函数创建Javascript对象

[英]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. 我知道可以使用多种方法在javascript中创建对象,并且我一直在阅读对象文字语法通常是首选。 (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") )? 我无法弄清楚的是,是否有理由使用其他任何方法来创建对象,例如自定义构造函数( 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. 但是,如果您创建自己的构造函数,则完全可以使用new关键字实例化它们,在那里没有争议。

You can use the custom constructor function when you want to create instances of objects, similar to Java. 当您要创建类似于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. 如果使用String文字,则需要将对象克隆到新的var中以获得另一个实例。

The preferred method would be to use JSON: var p = { "name":"Adam" }; 首选方法是使用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" };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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