1,Object.is():比较两个值是否严格相等,es5的‘===’,不能判断+0和-0,还有NaN,但是es6的Object.is()可以区分
Object.is(+0, -0); // false Object.is(NaN, NaN); // true
2,Object.assign():将源对象所有的可枚举的属性复制到目标对象。这个非常重要!
Object.assign(target, source1, source2......);第一个参数是目标对象,后面的参数都是源对象。
这是一种浅拷贝,不能达到我们期望的深拷贝,例如:
var target = {a: {b: 'c', d: 'e'}} var source = {a: {b: 'hello'}} Object.assign(target, source); // {a: {b: 'hello'}}
有参考说深拷贝可以用lodash的defaultsDeep,但是它有个缺陷就是同名属性不会覆盖。
3,属性的遍历
for...in:对象自身和继承的可枚举属性
Object.keys(obj):返回一个数组,包括对象自身的(不含继承的)所有可枚举属性(不含Symbol属性)
Object.getOwnPropertyNames(obj):返回一个数组,包含对象自身的所有属性(不含Symbol属性,但是包括不可枚举属性)
Object.getOwnPropertySymbols(obj):返回一个数组,包含对象自身的所有Symbol属性
Reflect.ownKeys(obj):返回一个数组,包含对象自身的所有属性,不管属性名是Symbol还是字符串,也不管是否可枚举
4,IE11已经支持__proto__属性
5,Object.setPrototypeOf():用来设置一个对象的prototype对象,返回参数对象本身。它是ES6正式推荐的设置原型对象的方法!
Object.setPrototypeOf(object, prototype);
6,Object.getPrototypeOf():读取一个对象的prototype对象
=====
这里补充一个Object.create()方法:会使用指定的原型对象及其属性去创建一个新的对象。
Object.create(proto [, propertiesObject]);
第一个参数必须是null或对象,第二个参数可选,是Object.defineProperties()的第二个参数。
看一个实例:
// Shape - superclass function Shape() { this.x = 0; this.y = 0; } // superclass method Shape.prototype.move = function(x, y) { this.x += x; this.y += y; console.info('Shape moved.'); }; // Rectangle - subclass function Rectangle() { Shape.call(this); // call super constructor. } // subclass extends superclass Rectangle.prototype = Object.create(Shape.prototype); Rectangle.prototype.constructor = Rectangle; var rect = new Rectangle(); console.log('Is rect an instance of Rectangle?', rect instanceof Rectangle); // true console.log('Is rect an instance of Shape?', rect instanceof Shape); // true rect.move(1, 1); // Outputs, 'Shape moved.'
7,Object.keys(),这个是es5的方法,返回一个数组,成员是参数对象自身的(不含继承的所有可遍历属性的键名),这个有点类似于数组实例的keys(),但是那个方法返回的是Iterator Object,这个返回的是真数组。