Javascript中的Object.create(null) &创建新的顶级对象

Object.create(null) in Javascript & creating new top-level objects

本文关键字:创建 对象 Object 中的 create null Javascript      更新时间:2023-09-26

如果这个问题太模糊,请让我知道,我会把它删除或尝试添加更多的代码示例,谢谢!

这篇文章的灵感来自Yehuta Katz关于"理解原型"的文章

在Javascript中,你可以通过使用Object.create()来利用原型,这将产生依赖/继承,就像在许多面向对象语言中看到的那样。如果将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"

构建{}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方法中可能很有用。