我应该使用对象文字或构造函数吗? [英] Should I be using object literals or constructor functions?

查看:88
本文介绍了我应该使用对象文字或构造函数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对在javascript中创建对象的方式感到困惑。似乎至少有两种方式。一种是使用对象文字符号,而另一种是使用构造函数。一个优于另一个吗?

I am getting confused over which way I should be creating an object in javascript. It seems there are at least two ways. One is to use object literal notation while the other uses construction functions. Is there an advantage of one over the other?

推荐答案

如果您没有与对象关联的行为(即如果对象只是数据/状态的容器,我会使用对象文字。

If you don't have behaviour associated with an object (i.e. if the object is just a container for data/state), I would use an object literal.

var data = {
    foo: 42,
    bar: 43
};

应用 KISS原则。如果除了简单的数据容器之外不需要任何东西,请使用简单的文字。

Apply the KISS principle. If you don't need anything beyond a simple container of data, go with a simple literal.

如果要向对象添加行为,可以使用构造函数并在构造期间向对象添加方法或为您的类提供原型。

If you want to add behaviour to your object, you can go with a constructor and add methods to the object during construction or give your class a prototype.

function MyData(foo, bar) {
    this.foo = foo;
    this.bar = bar;

    this.verify = function () {
        return this.foo === this.bar;
    };
}

// or:
MyData.prototype.verify = function () {
    return this.foo === this.bar;
};

像这样的类也像数据对象的模式一样:你现在有某种契约(通过构造函数)对象初始化/包含的属性。免费文字只是一个无定形的数据。

A class like this also acts like a schema for your data object: You now have some sort of contract (through the constructor) what properties the object initializes/contains. A free literal is just an amorphous blob of data.

您可能还有一个外部的验证函数在一个普通的旧数据对象上:

You might as well have an external verify function that acts on a plain old data object:

var data = {
    foo: 42,
    bar: 43
};

function verify(data) {
    return data.foo === data.bar;
}

然而,这在封装方面不利:理想情况下,所有数据+与实体相关的行为应该共存。

However, this is not favorable with regards to encapsulation: Ideally, all the data + behaviour associated with an entity should live together.

这篇关于我应该使用对象文字或构造函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆