Object 的几个方法整理

117 阅读2分钟

近日来都在看源码,看着源码里大佬们一些大佬们原生方法用的不亦乐乎,便整理一下Object的原生方法。

最详细的肯定是上MDN上直接看吧,但有时候会想不到能用在那些场景。我自己是整理了一些看到的地方。

Object MDN 介绍传送门

Object.defineProperty

Object.defineProperty(obj, prop, descriptor)
在obj上添加或修改属性prop, 并可定义该属性的descriptor描述符。描述符含义如下

  • configurable 决定该属性描述符是否可修改,默认true
  • enumrable 为true是才能出现在对象的枚举属性中,默认为false
  • value 该属性对应的值,数据描述,不能与get, set同时存在,默认undefined
  • writable 该属性value是否可修改,默认false
  • get 给属性提供getter方法,方法执行时只会传入this(不保证是该属性对象),默认undefined
  • set 属性值被修改时触发该方法,唯一参数为新修改值,默认undefined

Object assign

Object assing(target, ...source) 将所有可枚举属性的值从一个或多个源对象复制到目标对象。它将返回目标对象。注意这里的复制是浅复制,如果目标对象中的属性具有相同的键,则属性将被源对象中的属性覆盖。后面的源对象的属性将类似地覆盖前面的源对象的属性。 MDN上还提供了ES5的polyfill

if (typeof Object.assign != 'function') {
  // Must be writable: true, enumerable: false, configurable: true
  Object.defineProperty(Object, "assign", {
    value: function assign(target, varArgs) { // .length of function is 2
      'use strict';
      if (target == null) { // TypeError if undefined or null
        throw new TypeError('Cannot convert undefined or null to object');
      }

      let to = Object(target);

      for (var index = 1; index < arguments.length; index++) {
        var nextSource = arguments[index];

        if (nextSource != null) { // Skip over if undefined or null
          for (let nextKey in nextSource) {
            // Avoid bugs when hasOwnProperty is shadowed
            if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
              to[nextKey] = nextSource[nextKey];
            }
          }
        }
      }
      return to;
    },
    writable: true,
    configurable: true
  });
}

Object.prototype.hasOwnProperty

用来判断某个对象是否有指定的属性,返回Boolean

Object.keys

返回一个由一个给定对象的自身可枚举属性组成的数组,数组中属性名的排列顺序和使用 for...in 循环遍历该对象时返回的顺序一致

let arr = {
    a: 1,
    b: 2,
    c: 3
};
Object.keys(arr);           // ['a', 'b', 'c']