Object.create()、new Object()和{}的区别

131 阅读1分钟

1.new Object()和{}其实是一样的,都继承了 Object原型链上(Object.prototype)的属性和方法。因为二者一样,只用{}的使用举例。

var a={x:1}
console.log(a)   //{x: 1} 
console.log(a.__proto__)  //{constructor: ƒ, __defineGetter__: ƒ, __defineSetter__: ƒ, hasOwnProperty: ƒ, __lookupGetter__: ƒ, …}

2.使用Object.create()会将创建出来的对象继承到原型链上,而不是继承Object.prototype的属性和方法。

var c=Object.create({x:1})
console.log(c)       //{} 结果为空对象
console.log(c.x)     //{x: 1} 但能正常拿到对象的数据
console.log(c.__proto__)    //{x: 1}     //尝试拿到它的__proto__就知道原来是创建出来的对象继承到了原型链上
console.log(c.__proto__.__proto__)   //{constructor: ƒ, __defineGetter__: ƒ, __defineSetter__: ƒ, hasOwnProperty: ƒ, __lookupGetter__: ƒ, …}
                                     //再向上取它的__proto__才是原型上的属性和方法

拓展

可以用Object.create()做一些事情,比如:

var fn={
    something: function() {
        console.log( "do" );
    }
}
var b=Object.create(fn);
b.x=11;
console.log(b)    //{x: 11}  后续添加的x可以直接看到,而且这是b这个对象的,不与其他对象共享。

var d=new Object(fn);
console.log(d.x)   //undefined 这里就可以看到x不被共享,因为x不在d的原型链上。

d.y=2
var e=new Object(fn);
console.log(e.y)   //2  而new Object()方法构建的对象之间是共享y的。

console.log(fn)  //{y: 2, something: ƒ}  fn原型上也被添加了y,这也是d和e对象共享y的原因。

console.log(b.y)   //2  在b对象的原型链上,也是可以找到y的,只不过隔了一层原型链。