chdyiboke / weekly

issue and share weekly
5 stars 1 forks source link

js,如何创建一个纯净的对象? #28

Open chdyiboke opened 4 years ago

chdyiboke commented 4 years ago

ocn = Object.create( null )

chdyiboke commented 4 years ago

ocn = Object.create( null ); // 纯净的对象 ocn.prototype.toString = Object.toString; // Error: Cannot set property 'toString' of undefined

chdyiboke commented 4 years ago

Polyfill :

if (typeof Object.create !== "function") { Object.create = function (proto, propertiesObject) { if (typeof proto !== 'object' && typeof proto !== 'function') { throw new TypeError('Object prototype may only be an Object: ' + proto); } else if (proto === null) { throw new Error("This browser's implementation of Object.create is a shim and doesn't support 'null' as the first argument."); } if (typeof propertiesObject != 'undefined') { throw new Error("This browser's implementation of Object.create is a shim and doesn't support a second argument."); }

    function F() {}
    F.prototype = proto;

    return new F();
};

}

Polyfill 是一块代码(通常是 Web 上的 JavaScript),用来为旧浏览器提供它没有原生支持的较新的功能。

chdyiboke commented 4 years ago

扩展运算符的解构赋值,只能读取对象o自身的属性

const o = Object.create({ x: 1, y: 2 }); o.z = 3;

let { x, ...newObj } = o; let { y, z } = newObj; x // 1 y // undefined z // 3

o {z: 3}z: 3 proto: x: 1y: 2 proto: Object