How JavaScript Works 学习笔记 —— How object Works

325 阅读2分钟

在 JS 中,Object 非常特殊。

  • JS 中,everything is an object。当然,其实除了 null 和 undefined.
  • Object is a container of properties. Property 有 name 和 value 组成。Name 是 string, value 可以是任意类型。 其实,JS 中 object 的定义是非常宽泛和简介的,比如相同的概念,在其他语言中就会包含:hash table, map, record, dictionary 等等。在 JS 中,非常简介的 {name: value} 就已经表达了含义。

Copy

Object.assign 可以用来做 object 的复制。比如:

const newOject = Object.assign({}, oldObj);

Inheritance

在 JS 中,我们可以非常简单的让一个 Object 继承另一个 Object 的内容。而不需要通过复杂的 class 继承实现。比如: Object2 需要能偶继承 Object1 上的内容:

const object2 = Object.create(object1);

实际上做的内容也简单,create 一个新的 object2,并且把 object2 的 prototype 设置为 object1.

类似的实现:
const object2 = {};
Object.setPrototypeOf(object2, object1)

实际上,JS 中,我们通常会把某一个类型的 methods 放在 prototype 供具体的实例调用。比如说,Array 上所有的方法,也都定义在 Array.prototype 上,number 与 Number.prototype。

Object 取值都是先看 Object 本身是否有某个 property name,如果不存在,就检查 prototype。如果没有,再检查 prototype 的 prototype。

而且因为 JS 中 everything is an object, prototype chain 的重点,都是 Object.pototype。

这样,对于一个 object 而言,它的 property 就分为两种,自己的 property 和 prototype 上的 property。我们该如何区分呢?

我们发现,Object.proptype.hasOwnProperty(string) 的存在。因为所有的 object 本质上都会继承 Object.prototype, 我们在任何 oobject 都可以直接调用这个方法,来检查某个字段是否是当前 object 自有的 property。当然,前提是 hasOwnProperty 没有覆盖。

甚至,你有可能需要创建一个值包含 own property 的 object。很容易,将 prototype 设置为 null 就可以了。

const newObject = {};
Object.setPrototypeOf(newObject, null)

// OR
const newObject = Object.create(null);

Keys

Object.keys 能得到所有的 own property names