javascript - 创建 javascript 对象的两种方法,我应该使用哪一种?

标签 javascript

这些是创建 javascript 对象的方法:

function apple(optional_params) {
    this.type = "macintosh";
    this.color = "red";
    this.getInfo = function () {
        return this.color + ' ' + this.type + ' apple';
    };
}

var apple = {
    type: "macintosh",
    color: "red",
    getInfo: function() {
        return this.color + ' ' + this.type + ' apple';
    }
}

我真的更喜欢后者,因为它是 Json 语法,但我看到的第一个比后者多。

  • 它们在功能上有什么区别吗?
  • 能否对它们中的每一个进行扩展、继承和克隆/复制?
  • 在后一个中我可以轻松创建嵌套元素,这在第一个中可行吗?
  • 在后一个中我不能传递可选参数?
  • 它们的用途不同吗?如果是,您能否给出我会使用其中任何一个的场景。

最佳答案

区别在于您可以重复使用第一个。示例:

function Apple(type, color) {
  this.type = type;
  this.color = color;
  this.getInfo = function () {
    return this.color + ' ' + this.type + ' apple';
  }
}

var red = new Apple("Macintosh", "red");
var green = new Apple("Granny Smith", "green");

对比

var red = {
  type: "Macintosh",
  color: "red",
  getInfo: function() {
    return this.color + ' ' + this.type + ' apple';
  }
};

var green = {
  type: "Granny Smith",
  color: "green",
  getInfo: function() {
    return this.color + ' ' + this.type + ' apple';
  }
};

关于javascript - 创建 javascript 对象的两种方法,我应该使用哪一种?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3784729/

相关文章:

javascript - 存活时保留 Node 应用程序的数据

javascript - 如何从 '[object Object]' 字符串获取 JavaScript 对象?

javascript - jQuery 对话框不响应键盘按下

javascript - 在 jQuery 中绑定(bind)多个事件

javascript - Lodash 对象索引

javascript - 如何修复错误: Could not find router reducer in state tree,它必须安装在 "router"下

javascript - Odoo - 引发 javascript 警告

javascript - 序列化 HTML 元素有什么聪明的方法吗? - Javascript

javascript - 隐藏表中没有 ID 的特定行

javascript - 为必须以 3 个字母作为前缀的数字创建模式,例如 (IKA111111)