简体   繁体   English

Javascript对象初始化,这是最好的方法吗?

[英]Javascript object initialization, which is the best way to do it?

Object initialization: 对象初始化:

var myObject = {};

and

var myObject = new Object();

why the last one is considered an antipattern? 为什么最后一个被认为是反模式?

thanks 谢谢

I'm not sure new Object() really falls under "anti-pattern", but {} is usually preferred, it's terse and more flexible at the same time. 我不确定new Object()真的属于“反模式”,但{}通常是首选,它同时简洁且更灵活。

When you're writing JavaScript you want it to end up short...if it can be terse and understandable when writing it as well, as this is: 当你编写JavaScript时,你希望它最终简短...如果它在编写时也可以简洁易懂,因为这是:

var myObject = { key: "value" };

...then you get the best of both worlds. ......然后你将获得两全其美。 Also when you're creating objects within objects, for example: 当您在对象中创建对象时,例如:

var myObject = { subObj: { key: "value" } };

...then you can see it's much more readable than the alternative new Object() syntax. ...然后就可以看到它比其他具有可读性new Object()的语法。

You always should prefer literals over constructors. 你总是应该更喜欢文字而不是构造函数。

This is not really related to your question but here is an example with arrays. 这与您的问题无关,但这是一个数组示例。 new Array() can be confusing at the first glance if you don't know how it works: 如果你不知道它是如何工作的,那么new Array()乍一看可能会令人困惑:

var a = [5,6];
var b = [5];

both create arrays with length 2 and 1 resp. 两者都创建长度为2和1的数组。 But consider 但考虑一下

var a = new Array(5,6);
var b = new Array(5);

The first one creates an array of length 2 ,containing the elements 5 and 6, the last one creates an empty array of length 5. 第一个创建一个长度为2的数组,包含元素5和6,最后一个创建一个长度为 5的数组。

So you see, using literal notation avoids this pitfall. 所以你看,使用文字符号避免了这个陷阱。

Besides that, always using literal notation is consistent. 除此之外,始终使用文字符号是一致的。 When you create a string you also write var t = "Hello world" and not var t = new String("Hello world") . 创建字符串时,还要编写var t = "Hello world"而不是var t = new String("Hello world")

由于数组构造函数的问题,反模式很好,只是仍然使用文字{} ,而不是对象new Object的构造函数, 请参阅Google Javascript指南

Almost Always, yes 几乎总是,是的

I think saying things like "one should always prefer this" is a bit too generalized, there are always exceptions. 我认为说“一个人应该总是喜欢这个”这样的事情有点过于笼统,总有例外。 Object literals are almost always preferred, but what to do when you are trying to clone complex sets of objects?? 对象文字几乎总是首选,但是当你试图克隆复杂的对象集时该怎么办? Or trying to instantiate module ? 或者尝试实例化模块

if (typeof Object.create !== 'function') {
    Object.create = function (o) {
        function F() {}
        F.prototype = o;
        return new F();
    };
}
newObject = Object.create(oldObject);

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

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