Object.is(a, b)
讲到这个方法之前,首先要再谈到一下==和===的区别
(如果你还在代码中写== -_-!)
==: 在比较的时候会自动转换类型,才去比较。
===: 唯一的缺点就是NaN不等于自身,+0和-0相等。
而ES6增加了Object.is(a, b)这个方法:
console.log(+0 === -0);
console.log(NaN === NaN);
console.log(Object.is(+0, -0));
console.log(Object.is(NaN, NaN));
Object.assign(target, source…)
你肯定要问,这个函数是干什么用的?
复制一个或多个源对象的所有可枚举的属性的值到目标对象。
可能这里萌新有点蒙了,听我慢慢道来:
大家声明变量的时候多是这样写的吧:(多进入es6了,我就用let了)
let s1 = {
name: 'dai'
}
其实这里的对象字面量隐藏了很多东西,我们可以让它显出原形:
Object.getOwnPropertyDescriptor(s1, 'name')
实际上我们在声明变量的时候可以采用ES5中的Object.defineProperty(obj, name, config)
let obj = {};
Object.defineProperty(obj, 'name', {
value: 'xiaoming',
configurable: false,
writable: false,
enumerable: false
});
console.log(obj);
delete obj.name;
obj.name = "new";
for(let i in obj) {
if(obj.hasOwnProperty(i)) {
console.log(i);
}
}
大家要问这里与Object.assign()有什么关系,大哥你是不是跑题了。
这里的enumerable很重要,在ES6之前, 忽略enumerable为false的属性的情况:
(1)for in
(2)Object.keys() (只需要自身的属性,可以用此方法代替forin)
(3)JSON.stringify()
ES6中又新增了一种:
Object.assign();
(class中的原型方法也是不可以枚举的)
Object.assign()主要用来拷贝对象。例如:
let s1 = {};
Object.defineProperty(s1, 'name', {
value: 'xiaoming',
configurable: true,
enumerable: true,
writable: true
});
Object.defineProperty(s1, 'age', {
value: 21,
configurable: true,
enumerable: false,
writable: true
});
let s2 = Object.assign({},s1);
console.log(s2);
这里的Object.assign()拷贝的性质还是属于浅拷贝,如果你需要深拷贝的话:
let s1 = {
name: 'xiaoming',
age: 21,
info: {
childhood: {
name: 'xiao'
},
youth: {
name: 'xiaoming'
}
}
}
let s2 = JSON.parse(JSON.stringify(s1));
console.log(s1 === s2);
console.log(s1.info === s2.info);
Object.setPrototypeOf()
首先要介绍一下,__proto__是一个内部属性,用来操作prototype。
直接使用prototype不是特别好,于是出了几个代替的方法:
1、Object.setPrototypeOf() 写操作(ES6)
2、Object.getPrototypeOf() 读操作(ES5)
3、Object.create() 生成操作(ES5)
---------------------------
Object.getPrototypeOf
---------------------------
function People(){};
let p = new People();
console.log(Object.getPrototypeOf(p) === People.prototype);
--------------------
Object.create()
--------------------
let o = {};
-----------------------------
Object.setPrototypeOf()
-----------------------------
let fa = {};
let ch = {
x: 10
}
Object.setPrototypeOf(ch, fa);
fa.y = 20;
console.log(ch.y);