1、Object.create(prototype[,propertiesObject]):第一个参数为对象,对象为函数调用之后返回新对象的原型对象,第二个参数为对象本身的实例方法(默认不能修改,不能枚举)
const obj = Object.create({a:1}, {b: {value: 2}});
obj.__proto__.a === 1 // true
obj.b = 3;
console.log(obj.b) // 2
2、Object.defineProperty(object, prop, descriptor)
var obj = {};
// 1.添加一个数据属性
Object.defineProperty(obj, "newDataProperty", {
value: 101,
writable: true,
enumerable: true,
configurable: true
});
// 2.修改数据属性
Object.defineProperty(obj, "newDataProperty", {
writable:false
});
// 3.劫持访问器属性
Object.defineProperty(obj, "newAccessorProperty", {
set: function (x) {
this.otherProperty = x;
},
get: function () {
return this.otherProperty;
},
enumerable: true,
configurable: true
});
3、Boolean hasOwnProperty(key): 对象自身属性中是否具有指定的属性,返回布尔值。
let o = {a: 1 }
o.hasOwnProperty('a') //true
o.hasOwnProperty('b') //false 对象自身没有属性b
o.hasOwnProperty('toString'); //false 不能检测对象原型链上的属性
4、getOwnPropertyDescriptor(obj, prop): 返回指定对象上一个自有属性对应的属性描述符。
let obj = { foo: 123 };
Object.getOwnPropertyDescriptor(obj, 'foo')
// { value: 123, writable: true, enumerable: true, configurable: true }
5、getOwnPropertyDescriptors(obj): 返回指定对象上所有自有属性对应的属性描述符。
const obj = {
foo: 123,
get bar() { return 'abc' }
};
console.dir(Object.getOwnPropertyDescriptors(obj))
// {
// foo:{ value: 123,
// writable: true,
// enumerable: true,
// configurable: true
// },
// bar:{
// get: [Function: bar],
// set: undefined,
// enumerable: true,
// configurable: true
// }
// }
6、getPrototypeOf(obj): 获取一个对象的原型在 chrome 中可以通过_proto_的形式,或者在 ES6 中可以通过 Object.getPrototypeOf 的形式。
const prototype1 = {};
const object1 = Object.create(prototype1);
console.log(Object.getPrototypeOf(object1) === prototype1); // true
// 需要注意的地方
Object.getPrototypeOf(new Object()) === Object.prototype // true
Object.getPrototypeOf(Object) === Object.prototype // false
Object.getPrototypeOf(Object) === Function.prototype; // true
7、is(obj1, obj2): 用来比较两个值是否严格相等,与严格比较运算符(===)的行为基本一致。
Object.is('foo', 'foo') // true
Object.is({}, {}) // false
// ==、===、Object.is之间的区别
+0 === -0 //true
NaN === NaN // false
Object.is(+0, -0) // false
Object.is(NaN, NaN) // true
// ==在比较时,会将值强制转换成number、null==undefined
" " == 0 //true
"0" == 0 //true
" " != "0" //true
123 == "123" //true
null == undefined //true