“new Object()”和对象文字表示法之间的区别是什么?

时间:2022-12-13 22:28:28

What is the difference between this constructor-based syntax for creating an object:

这种基于构造函数的创建对象的语法有什么不同:

person = new Object()

...and this literal syntax:

…这文字的语法:

person = {
    property1 : "Hello"
};

It appears that both do the same thing, although JSLint prefers you use object literal notation.

看起来两者都做同样的事情,尽管JSLint更喜欢使用对象文字表示法。

Which one is better and why?

哪一个更好,为什么?

9 个解决方案

#1


98  

They both do the same thing (unless someone's done something unusual), other than that your second one creates an object and adds a property to it. But literal notation takes less space in the source code. It's clearly recognizable as to what is happening, so using new Object(), you are really just typing more and (in theory, if not optimized out by the JavaScript engine) doing an unnecessary function call.

它们都做相同的事情(除非有人做了不寻常的事情),除了第二个创建一个对象并向其添加属性。但是文字符号在源代码中占用的空间更少。对于正在发生的事情,很明显是可以理解的,所以使用new Object(),您实际上只是输入了更多的内容,并且(在理论上,如果不是由JavaScript引擎优化的话)进行了不必要的函数调用。

These

这些

person = new Object() /*You should put a semicolon here too.  
It's not required, but it is good practice.*/ 
-or-

person = {
    property1 : "Hello"
};

technically do not do the same thing. The first just creates an object. The second creates one and assigns a property. For the first one to be the same you then need a second step to create and assign the property.

技术上不要做同样的事情。第一个只是创建一个对象。第二个创建一个并分配一个属性。对于第一个相同的属性,则需要第二个步骤来创建和分配属性。

The "something unusual" that someone could do would be to shadow or assign to the default Object global:

有些人可以做的“不寻常的事情”是对默认对象全局进行阴影或分配:

// Don't do this
Object = 23;

In that highly-unusual case, new Object will fail but {} will work.

在这种高度不寻常的情况下,新对象将失败,但{}将工作。

In practice, there's never a reason to use new Object rather than {} (unless you've done that very unusual thing).

在实践中,从来没有理由使用新对象而不是{}(除非您已经做了非常不寻常的事情)。

#2


204  

There is no difference for a simple object without methods as in your example. However, there is a big difference when you start adding methods to your object.

没有方法的简单对象与示例中的方法没有区别。但是,当您开始向对象添加方法时,会有很大的不同。

Literal way:

文字:

function Obj( prop ) { 
    return { 
        p : prop, 
        sayHello : function(){ alert(this.p); }, 
    }; 
} 

Prototype way:

原型:

function Obj( prop ) { 
    this.p = prop; 
} 
Obj.prototype.sayHello = function(){alert(this.p);}; 

Both ways allow creation of instances of Obj like this:

两种方法都允许创建这样的Obj实例:

var foo = new Obj( "hello" ); 

However, with the literal way, you carry a copy of the sayHello method within each instance of your objects. Whereas, with the prototype way, the method is defined in the object prototype and shared between all object instances. If you have a lot of objects or a lot of methods, the literal way can lead to quite big memory waste.

但是,通过字面方式,您将在对象的每个实例中携带sayHello方法的副本。然而,使用原型方法,方法在对象原型中定义,并在所有对象实例之间共享。如果你有很多对象或方法,字面上的方法会导致很大的内存浪费。

#3


49  

In JavaScript, we can declare a new empty object in two ways:

在JavaScript中,我们可以用两种方式声明一个新的空对象:

var obj1 = new Object();  
var obj2 = {};  

I have found nothing to suggest that there is any significant difference these two with regard to how they operate behind the scenes (please correct me if i am wrong – I would love to know). However, the second method (using the object literal notation) offers a few advantages.

我没有发现任何迹象表明,这两家公司在幕后的运作方式有任何显著差异(如果我错了,请纠正我——我很想知道)。然而,第二个方法(使用对象文字符号)提供了一些优势。

  1. It is shorter (10 characters to be precise)
  2. 它更短(精确地说是10个字符)
  3. It is easier, and more structured to create objects on the fly
  4. 动态创建对象更容易,也更结构化
  5. It doesn’t matter if some buffoon has inadvertently overridden Object
  6. 不管某个小丑是否无意中覆盖了对象

Consider a new object that contains the members Name and TelNo. Using the new Object() convention, we can create it like this:

考虑一个包含成员名称和TelNo的新对象。使用新的Object()约定,我们可以这样创建它:

var obj1 = new Object();  
obj1.Name = "A Person";  
obj1.TelNo = "12345"; 

The Expando Properties feature of JavaScript allows us to create new members this way on the fly, and we achieve what were intending. However, this way isn’t very structured or encapsulated. What if we wanted to specify the members upon creation, without having to rely on expando properties and assignment post-creation?

JavaScript的Expando属性特性允许我们以这种方式动态创建新成员,并且实现了我们的目标。然而,这种方式并不是非常结构化或封装的。如果我们想在创建时指定成员,而不需要依赖于expando属性和分配post-creation,该怎么办?

This is where the object literal notation can help:

这就是对象文字符号可以帮助的地方:

var obj1 = {Name:"A Person",TelNo="12345"};  

Here we have achieved the same effect in one line of code and significantly fewer characters.

在这里,我们在一行代码中实现了同样的效果,并且显著减少了字符。

A further discussion the object construction methods above can be found at: JavaScript and Object Oriented Programming (OOP).

可以在JavaScript和面向对象编程(OOP)中找到上述对象构建方法的进一步讨论。

And finally, what of the idiot who overrode Object? Did you think it wasn’t possible? Well, this JSFiddle proves otherwise. Using the object literal notation prevents us from falling foul of this buffoonery.

最后,那个压倒一切的白痴呢?你认为这不可能吗?这个JSFiddle证明的是另一种情况。使用对象文字表示法可以防止我们与这个小丑发生冲突。

(From http://www.jameswiseman.com/blog/2011/01/19/jslint-messages-use-the-object-literal-notation/)

(来自http://www.jameswiseman.com/blog/2011/01/19/jslint-messages-use-the-object-literal-notation/)

#4


33  

On my machine using Node.js, I ran the following:

在我的机器上使用Node。js,我运行如下:

console.log('Testing Array:');
console.time('using[]');
for(var i=0; i<200000000; i++){var arr = []};
console.timeEnd('using[]');

console.time('using new');
for(var i=0; i<200000000; i++){var arr = new Array};
console.timeEnd('using new');

console.log('Testing Object:');

console.time('using{}');
for(var i=0; i<200000000; i++){var obj = {}};
console.timeEnd('using{}');

console.time('using new');
for(var i=0; i<200000000; i++){var obj = new Object};
console.timeEnd('using new');

Note, this is an extension of what is found here: Why is arr = [] faster than arr = new Array?

注意,这是这里的扩展:为什么arr =[]比arr = new Array要快?

my output was the following:

我的输出如下:

Testing Array:
using[]: 1091ms
using new: 2286ms
Testing Object:
using{}: 870ms
using new: 5637ms

so clearly {} and [] are faster than using new for creating empty objects/arrays.

显然,{}和[]比使用new创建空对象/数组要快。

#5


25  

Everyone here is talking about the similarities of the two. I am gonna point out the differences.

这里的每个人都在谈论这两者的相似之处。我要指出不同之处。

  1. Using new Object() allows you to pass another object. The obvious outcome is that the newly created object will be set to the same reference. Here is a sample code:

    使用new Object()允许您传递另一个对象。显而易见的结果是,新创建的对象将被设置为相同的引用。下面是一个示例代码:

    var obj1 = new Object();
    obj1.a = 1;
    var obj2 = new Object(obj1);
    obj2.a // 1
    
  2. The usage is not limited to objects as in OOP objects. Other types could be passed to it too. The function will set the type accordingly. For example if we pass integer 1 to it, an object of type number will be created for us.

    这种用法并不仅限于对象,如在OOP对象中。其他类型也可以传递给它。函数将相应地设置类型。例如,如果我们将integer 1传递给它,就会为我们创建一个类型为number的对象。

    var obj = new Object(1);
    typeof obj // "number"
    
  3. The object created using the above method (new Object(1)) would be converted to object type if a property is added to it.

    如果添加了属性,则使用上述方法(new object(1))创建的对象将被转换为对象类型。

    var obj = new Object(1);
    typeof obj // "number"
    obj.a = 2;
    typeof obj // "object"
    
  4. If the object is a copy of a child class of object, we could add the property without the type conversion.

    如果对象是对象的子类的副本,我们可以添加属性,而不需要类型转换。

    var obj = new Object("foo");
    typeof obj // "object"
    obj === "foo" // true
    obj.a = 1;
    obj === "foo" // true
    obj.a // 1
    var str = "foo";
    str.a = 1;
    str.a // undefined
    

#6


13  

Actually, there are several ways to create objects in JavaScript. When you just want to create an object there's no benefit of creating "constructor-based" objects using "new" operator. It's same as creating an object using "object literal" syntax. But "constructor-based" objects created with "new" operator comes to incredible use when you are thinking about "prototypal inheritance". You cannot maintain inheritance chain with objects created with literal syntax. But you can create a constructor function, attach properties and methods to its prototype. Then if you assign this constructor function to any variable using "new" operator, it will return an object which will have access to all of the methods and properties attached with the prototype of that constructor function.

实际上,有几种方法可以在JavaScript中创建对象。当您只想创建一个对象时,使用“new”操作符创建“基于构造的”对象是没有好处的。这与使用“对象文字”语法创建对象是一样的。但是,当您考虑“原型继承”时,使用“new”操作符创建的“基于构造函数的”对象就会得到不可思议的使用。不能使用使用文字语法创建的对象来维护继承链。但是您可以创建一个构造函数,将属性和方法附加到原型中。然后,如果您使用“new”操作符将构造函数赋值给任何变量,它将返回一个对象,该对象将访问该构造函数的原型所附带的所有方法和属性。

Here is an example of creating an object using constructor function (see code explanation at the bottom):

下面是一个使用构造函数创建对象的示例(参见下面的代码说明):

function Person(firstname, lastname) {
    this.firstname = firstname;
    this.lastname = lastname;
}

Person.prototype.fullname = function() {
    console.log(this.firstname + ' ' + this.lastname);
}

var zubaer = new Person('Zubaer', 'Ahammed');
var john = new Person('John', 'Doe');

zubaer.fullname();
john.fullname();

Now, you can create as many objects as you want by instantiating Person construction function and all of them will inherit fullname() from it.

现在,您可以通过实例化Person构造函数来创建任意多的对象,所有的对象都将继承fullname()。

Note: "this" keyword will refer to an empty object within a constructor function and whenever you create a new object from Person using "new" operator it will automatically return an object containing all of the properties and methods attached with the "this" keyword. And these object will for sure inherit the methods and properties attached with the prototype of the Person constructor function (which is the main advantage of this approach).

注意:“this”关键字将引用构造函数中的一个空对象,每当您使用“new”操作符从Person创建一个新对象时,它将自动返回一个对象,该对象包含与“this”关键字附加的所有属性和方法。这些对象肯定继承了Person构造函数的原型所附带的方法和属性(这是这种方法的主要优点)。

By the way, if you wanted to obtain the same functionality with "object literal" syntax, you would have to create fullname() on all of the objects like below:

顺便说一下,如果你想用“对象文字”语法获得相同的功能,你必须在所有对象上创建fullname(),如下所示:

var zubaer = {
    firstname: 'Zubaer',
    lastname: 'Ahammed',
    fullname: function() {
        console.log(this.firstname + ' ' + this.lastname);
    }
};

var john= {
    firstname: 'John',
    lastname: 'Doe',
    fullname: function() {
        console.log(this.firstname + ' ' + this.lastname);
    }
};

zubaer.fullname();
john.fullname();

At last, if you now ask why should I use constructor function approach instead of object literal approach:

最后,如果你现在问为什么我应该使用构造函数方法而不是对象文字方法:

*** Prototypal inheritance allows a simple chain of inheritance which can be immensely useful and powerful.

**原型继承允许一个简单的继承链,它可以非常有用和强大。

*** It saves memory by inheriting common methods and properties defined in constructor functions prototype. Otherwise, you would have to copy them over and over again in all of the objects.

通过继承构造函数原型中定义的常用方法和属性来节省内存。否则,您将不得不在所有对象中反复复制它们。

I hope this makes sense.

我希望这说得通。

#7


8  

Also, according to some of the O'Really javascript books....(quoted)

另外,据O 'Really javascript的一些书籍....(引用)

Another reason for using literals as opposed to the Object constructor is that there is no scope resolution. Because it’s possible that you have created a local constructor with the same name, the interpreter needs to look up the scope chain from the place you are calling Object() all the way up until it finds the global Object constructor.

使用常量而不是对象构造函数的另一个原因是没有范围解析。因为您可能已经创建了一个具有相同名称的本地构造函数,所以解释器需要从调用Object()的位置一直查找范围链,直到找到全局对象构造函数为止。

#8


3  

I have found one difference, for ES6/ES2015. You cannot return an object using the shorthand arrow function syntax, unless you surround the object with new Object().

我发现ES6/ES2015有一个不同。不能使用速记箭头函数语法返回对象,除非使用new object()包围对象。

> [1, 2, 3].map(v => {n: v});
[ undefined, undefined, undefined ]
> [1, 2, 3].map(v => new Object({n: v}));
[ { n: 1 }, { n: 2 }, { n: 3 } ]

This is because the compiler is confused by the {} brackets and thinks n: i is a label: statement construct; the semicolon is optional so it doesn't complain about it.

这是因为编译器被{}括号搞糊涂了,认为n: i是一个label:语句构造;分号是可选的,所以它没有抱怨。

If you add another property to the object it will finally throw an error.

如果向对象添加另一个属性,最终将抛出一个错误。

$ node -e "[1, 2, 3].map(v => {n: v, m: v+1});"
[1, 2, 3].map(v => {n: v, m: v+1});
                           ^

SyntaxError: Unexpected token :

#9


-2  

Memory usage is different if you create 10 thousand instances. new Object() will only keep only one copy while {} will keep 10 thousand copies.

如果您创建10,000个实例,那么内存使用是不同的。新对象()将只保留一个副本,而{}将保留10,000个副本。

#1


98  

They both do the same thing (unless someone's done something unusual), other than that your second one creates an object and adds a property to it. But literal notation takes less space in the source code. It's clearly recognizable as to what is happening, so using new Object(), you are really just typing more and (in theory, if not optimized out by the JavaScript engine) doing an unnecessary function call.

它们都做相同的事情(除非有人做了不寻常的事情),除了第二个创建一个对象并向其添加属性。但是文字符号在源代码中占用的空间更少。对于正在发生的事情,很明显是可以理解的,所以使用new Object(),您实际上只是输入了更多的内容,并且(在理论上,如果不是由JavaScript引擎优化的话)进行了不必要的函数调用。

These

这些

person = new Object() /*You should put a semicolon here too.  
It's not required, but it is good practice.*/ 
-or-

person = {
    property1 : "Hello"
};

technically do not do the same thing. The first just creates an object. The second creates one and assigns a property. For the first one to be the same you then need a second step to create and assign the property.

技术上不要做同样的事情。第一个只是创建一个对象。第二个创建一个并分配一个属性。对于第一个相同的属性,则需要第二个步骤来创建和分配属性。

The "something unusual" that someone could do would be to shadow or assign to the default Object global:

有些人可以做的“不寻常的事情”是对默认对象全局进行阴影或分配:

// Don't do this
Object = 23;

In that highly-unusual case, new Object will fail but {} will work.

在这种高度不寻常的情况下,新对象将失败,但{}将工作。

In practice, there's never a reason to use new Object rather than {} (unless you've done that very unusual thing).

在实践中,从来没有理由使用新对象而不是{}(除非您已经做了非常不寻常的事情)。

#2


204  

There is no difference for a simple object without methods as in your example. However, there is a big difference when you start adding methods to your object.

没有方法的简单对象与示例中的方法没有区别。但是,当您开始向对象添加方法时,会有很大的不同。

Literal way:

文字:

function Obj( prop ) { 
    return { 
        p : prop, 
        sayHello : function(){ alert(this.p); }, 
    }; 
} 

Prototype way:

原型:

function Obj( prop ) { 
    this.p = prop; 
} 
Obj.prototype.sayHello = function(){alert(this.p);}; 

Both ways allow creation of instances of Obj like this:

两种方法都允许创建这样的Obj实例:

var foo = new Obj( "hello" ); 

However, with the literal way, you carry a copy of the sayHello method within each instance of your objects. Whereas, with the prototype way, the method is defined in the object prototype and shared between all object instances. If you have a lot of objects or a lot of methods, the literal way can lead to quite big memory waste.

但是,通过字面方式,您将在对象的每个实例中携带sayHello方法的副本。然而,使用原型方法,方法在对象原型中定义,并在所有对象实例之间共享。如果你有很多对象或方法,字面上的方法会导致很大的内存浪费。

#3


49  

In JavaScript, we can declare a new empty object in two ways:

在JavaScript中,我们可以用两种方式声明一个新的空对象:

var obj1 = new Object();  
var obj2 = {};  

I have found nothing to suggest that there is any significant difference these two with regard to how they operate behind the scenes (please correct me if i am wrong – I would love to know). However, the second method (using the object literal notation) offers a few advantages.

我没有发现任何迹象表明,这两家公司在幕后的运作方式有任何显著差异(如果我错了,请纠正我——我很想知道)。然而,第二个方法(使用对象文字符号)提供了一些优势。

  1. It is shorter (10 characters to be precise)
  2. 它更短(精确地说是10个字符)
  3. It is easier, and more structured to create objects on the fly
  4. 动态创建对象更容易,也更结构化
  5. It doesn’t matter if some buffoon has inadvertently overridden Object
  6. 不管某个小丑是否无意中覆盖了对象

Consider a new object that contains the members Name and TelNo. Using the new Object() convention, we can create it like this:

考虑一个包含成员名称和TelNo的新对象。使用新的Object()约定,我们可以这样创建它:

var obj1 = new Object();  
obj1.Name = "A Person";  
obj1.TelNo = "12345"; 

The Expando Properties feature of JavaScript allows us to create new members this way on the fly, and we achieve what were intending. However, this way isn’t very structured or encapsulated. What if we wanted to specify the members upon creation, without having to rely on expando properties and assignment post-creation?

JavaScript的Expando属性特性允许我们以这种方式动态创建新成员,并且实现了我们的目标。然而,这种方式并不是非常结构化或封装的。如果我们想在创建时指定成员,而不需要依赖于expando属性和分配post-creation,该怎么办?

This is where the object literal notation can help:

这就是对象文字符号可以帮助的地方:

var obj1 = {Name:"A Person",TelNo="12345"};  

Here we have achieved the same effect in one line of code and significantly fewer characters.

在这里,我们在一行代码中实现了同样的效果,并且显著减少了字符。

A further discussion the object construction methods above can be found at: JavaScript and Object Oriented Programming (OOP).

可以在JavaScript和面向对象编程(OOP)中找到上述对象构建方法的进一步讨论。

And finally, what of the idiot who overrode Object? Did you think it wasn’t possible? Well, this JSFiddle proves otherwise. Using the object literal notation prevents us from falling foul of this buffoonery.

最后,那个压倒一切的白痴呢?你认为这不可能吗?这个JSFiddle证明的是另一种情况。使用对象文字表示法可以防止我们与这个小丑发生冲突。

(From http://www.jameswiseman.com/blog/2011/01/19/jslint-messages-use-the-object-literal-notation/)

(来自http://www.jameswiseman.com/blog/2011/01/19/jslint-messages-use-the-object-literal-notation/)

#4


33  

On my machine using Node.js, I ran the following:

在我的机器上使用Node。js,我运行如下:

console.log('Testing Array:');
console.time('using[]');
for(var i=0; i<200000000; i++){var arr = []};
console.timeEnd('using[]');

console.time('using new');
for(var i=0; i<200000000; i++){var arr = new Array};
console.timeEnd('using new');

console.log('Testing Object:');

console.time('using{}');
for(var i=0; i<200000000; i++){var obj = {}};
console.timeEnd('using{}');

console.time('using new');
for(var i=0; i<200000000; i++){var obj = new Object};
console.timeEnd('using new');

Note, this is an extension of what is found here: Why is arr = [] faster than arr = new Array?

注意,这是这里的扩展:为什么arr =[]比arr = new Array要快?

my output was the following:

我的输出如下:

Testing Array:
using[]: 1091ms
using new: 2286ms
Testing Object:
using{}: 870ms
using new: 5637ms

so clearly {} and [] are faster than using new for creating empty objects/arrays.

显然,{}和[]比使用new创建空对象/数组要快。

#5


25  

Everyone here is talking about the similarities of the two. I am gonna point out the differences.

这里的每个人都在谈论这两者的相似之处。我要指出不同之处。

  1. Using new Object() allows you to pass another object. The obvious outcome is that the newly created object will be set to the same reference. Here is a sample code:

    使用new Object()允许您传递另一个对象。显而易见的结果是,新创建的对象将被设置为相同的引用。下面是一个示例代码:

    var obj1 = new Object();
    obj1.a = 1;
    var obj2 = new Object(obj1);
    obj2.a // 1
    
  2. The usage is not limited to objects as in OOP objects. Other types could be passed to it too. The function will set the type accordingly. For example if we pass integer 1 to it, an object of type number will be created for us.

    这种用法并不仅限于对象,如在OOP对象中。其他类型也可以传递给它。函数将相应地设置类型。例如,如果我们将integer 1传递给它,就会为我们创建一个类型为number的对象。

    var obj = new Object(1);
    typeof obj // "number"
    
  3. The object created using the above method (new Object(1)) would be converted to object type if a property is added to it.

    如果添加了属性,则使用上述方法(new object(1))创建的对象将被转换为对象类型。

    var obj = new Object(1);
    typeof obj // "number"
    obj.a = 2;
    typeof obj // "object"
    
  4. If the object is a copy of a child class of object, we could add the property without the type conversion.

    如果对象是对象的子类的副本,我们可以添加属性,而不需要类型转换。

    var obj = new Object("foo");
    typeof obj // "object"
    obj === "foo" // true
    obj.a = 1;
    obj === "foo" // true
    obj.a // 1
    var str = "foo";
    str.a = 1;
    str.a // undefined
    

#6


13  

Actually, there are several ways to create objects in JavaScript. When you just want to create an object there's no benefit of creating "constructor-based" objects using "new" operator. It's same as creating an object using "object literal" syntax. But "constructor-based" objects created with "new" operator comes to incredible use when you are thinking about "prototypal inheritance". You cannot maintain inheritance chain with objects created with literal syntax. But you can create a constructor function, attach properties and methods to its prototype. Then if you assign this constructor function to any variable using "new" operator, it will return an object which will have access to all of the methods and properties attached with the prototype of that constructor function.

实际上,有几种方法可以在JavaScript中创建对象。当您只想创建一个对象时,使用“new”操作符创建“基于构造的”对象是没有好处的。这与使用“对象文字”语法创建对象是一样的。但是,当您考虑“原型继承”时,使用“new”操作符创建的“基于构造函数的”对象就会得到不可思议的使用。不能使用使用文字语法创建的对象来维护继承链。但是您可以创建一个构造函数,将属性和方法附加到原型中。然后,如果您使用“new”操作符将构造函数赋值给任何变量,它将返回一个对象,该对象将访问该构造函数的原型所附带的所有方法和属性。

Here is an example of creating an object using constructor function (see code explanation at the bottom):

下面是一个使用构造函数创建对象的示例(参见下面的代码说明):

function Person(firstname, lastname) {
    this.firstname = firstname;
    this.lastname = lastname;
}

Person.prototype.fullname = function() {
    console.log(this.firstname + ' ' + this.lastname);
}

var zubaer = new Person('Zubaer', 'Ahammed');
var john = new Person('John', 'Doe');

zubaer.fullname();
john.fullname();

Now, you can create as many objects as you want by instantiating Person construction function and all of them will inherit fullname() from it.

现在,您可以通过实例化Person构造函数来创建任意多的对象,所有的对象都将继承fullname()。

Note: "this" keyword will refer to an empty object within a constructor function and whenever you create a new object from Person using "new" operator it will automatically return an object containing all of the properties and methods attached with the "this" keyword. And these object will for sure inherit the methods and properties attached with the prototype of the Person constructor function (which is the main advantage of this approach).

注意:“this”关键字将引用构造函数中的一个空对象,每当您使用“new”操作符从Person创建一个新对象时,它将自动返回一个对象,该对象包含与“this”关键字附加的所有属性和方法。这些对象肯定继承了Person构造函数的原型所附带的方法和属性(这是这种方法的主要优点)。

By the way, if you wanted to obtain the same functionality with "object literal" syntax, you would have to create fullname() on all of the objects like below:

顺便说一下,如果你想用“对象文字”语法获得相同的功能,你必须在所有对象上创建fullname(),如下所示:

var zubaer = {
    firstname: 'Zubaer',
    lastname: 'Ahammed',
    fullname: function() {
        console.log(this.firstname + ' ' + this.lastname);
    }
};

var john= {
    firstname: 'John',
    lastname: 'Doe',
    fullname: function() {
        console.log(this.firstname + ' ' + this.lastname);
    }
};

zubaer.fullname();
john.fullname();

At last, if you now ask why should I use constructor function approach instead of object literal approach:

最后,如果你现在问为什么我应该使用构造函数方法而不是对象文字方法:

*** Prototypal inheritance allows a simple chain of inheritance which can be immensely useful and powerful.

**原型继承允许一个简单的继承链,它可以非常有用和强大。

*** It saves memory by inheriting common methods and properties defined in constructor functions prototype. Otherwise, you would have to copy them over and over again in all of the objects.

通过继承构造函数原型中定义的常用方法和属性来节省内存。否则,您将不得不在所有对象中反复复制它们。

I hope this makes sense.

我希望这说得通。

#7


8  

Also, according to some of the O'Really javascript books....(quoted)

另外,据O 'Really javascript的一些书籍....(引用)

Another reason for using literals as opposed to the Object constructor is that there is no scope resolution. Because it’s possible that you have created a local constructor with the same name, the interpreter needs to look up the scope chain from the place you are calling Object() all the way up until it finds the global Object constructor.

使用常量而不是对象构造函数的另一个原因是没有范围解析。因为您可能已经创建了一个具有相同名称的本地构造函数,所以解释器需要从调用Object()的位置一直查找范围链,直到找到全局对象构造函数为止。

#8


3  

I have found one difference, for ES6/ES2015. You cannot return an object using the shorthand arrow function syntax, unless you surround the object with new Object().

我发现ES6/ES2015有一个不同。不能使用速记箭头函数语法返回对象,除非使用new object()包围对象。

> [1, 2, 3].map(v => {n: v});
[ undefined, undefined, undefined ]
> [1, 2, 3].map(v => new Object({n: v}));
[ { n: 1 }, { n: 2 }, { n: 3 } ]

This is because the compiler is confused by the {} brackets and thinks n: i is a label: statement construct; the semicolon is optional so it doesn't complain about it.

这是因为编译器被{}括号搞糊涂了,认为n: i是一个label:语句构造;分号是可选的,所以它没有抱怨。

If you add another property to the object it will finally throw an error.

如果向对象添加另一个属性,最终将抛出一个错误。

$ node -e "[1, 2, 3].map(v => {n: v, m: v+1});"
[1, 2, 3].map(v => {n: v, m: v+1});
                           ^

SyntaxError: Unexpected token :

#9


-2  

Memory usage is different if you create 10 thousand instances. new Object() will only keep only one copy while {} will keep 10 thousand copies.

如果您创建10,000个实例,那么内存使用是不同的。新对象()将只保留一个副本,而{}将保留10,000个副本。