【问题标题】:Object.create(null) in Javascript & creating new top-level objects [duplicate]Javascript中的Object.create(null)和创建新的顶级对象[重复]
【发布时间】:2014-07-10 14:03:59
【问题描述】:

如果这个问题太模糊,请告诉我,我会记下来或尝试添加更多代码示例,谢谢!

这篇文章的灵感来自Yehuta Katz' article on "Understanding Prototypes"

在 Javascript 中,您可以通过使用 Object.create() 来利用原型,这将产生类似于许多 OOP 语言中的依赖/继承。如果null 的参数传递给create() 方法,那么这个新对象将是顶级对象,与Object.prototype 处于同一级别。

现在,也许这只是我使用 Java 和 C# 的几年,但是什么时候会创建一个顶级对象呢?如果您对Object.prototype 中的字段/方法不满意,为什么不直接扩展它并制作您自己的伪顶级对象?

示例: 在这个例子中,person 是一个顶级对象。因此,它没有继承Object.prototype中包含的标准方法,例如toString()hasOwnProperty()valueOf()等。

var person = Object.create(null);

// instead of using defineProperty and specifying writable,
// configurable, and enumerable, we can just assign the
// value directly and JavaScript will take care of the rest
person['fullName'] = function() {
  return this.firstName + ' ' + this.lastName;
};

// this time, let's make man's prototype person, so all
// men share the fullName function
var man = Object.create(person);
man['sex'] = "male";

var yehuda = Object.create(man);
yehuda['firstName'] = "Yehuda";
yehuda['lastName'] = "Katz";

yehuda.sex        // "male"
yehuda.fullName() // "Yehuda Katz"

【问题讨论】:

  • 一般?当你想避免意外时——(例如使用地图对象)——你希望在真实对象中出现这种情况的实际情况非常罕见。

标签: javascript inheritance prototype


【解决方案1】:

如您所说,构造 {}new Object 会产生一个具有原型的对象。使用Object.create(null) 构造会构建一个具有空原型的对象,因此没有继承成员。

我能想到的一个很好的用例是当你实际上需要一个绝对无成员的对象时,例如,执行一个安全的迭代:

for(var key in obj) {
    /*
      in normal conditions, you must ensure that object hasOwnProperty(key)
      so you know you're iterating on actual members.
     */
     if (obj.hasOwnProperty(key)) {
         console.log("key: " + key + "; value: " + obj[key]);
     }
}

但是通过这种方法,您可以确保您没有任何原型,因此默认情况下每个属性都将是自己的。

obj = Object.create(null);
//to-do populate your object keys here, treating it like a hash instead of an object.
for(var key in obj) {
     /*
       this operation is safe and also this object is safe to be populated
       in server-side javascript (e.g. nodejs) via a POST request.
       a common use case is to SERIALIZE this object quickly, while the
       previous IF could provide some overhead.
     */
     console.log("key: " + key + "; value: " + obj[key]);
}

因此,您可以安全地将对象视为哈希并按照我所说的进行迭代,只保存真实数据。

另一个可能的用例是当您想从头开始构建自己的原型(甚至是 toString 函数或不在对象原型中定义某些函数)并创建全新的层次结构时。这可能仅对框架有用。这有点麻烦,但在 OOP 方法中可能很有用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-08
    • 2023-04-08
    • 2017-12-17
    相关资源
    最近更新 更多