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

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

创建对象的方法:

    创建一个空对象有以下三个方法:

varobj1 = {};varobj2 = Object.create(null);varobj3 =newObject();

创建空对象的区别:

    要创建一个干净的空对象,应该使用Object.create(null)而不是剩下两种。

   通过做Object.create(null),我们可以显式指定null作为它的原型。所以它绝对没有属性,

甚至没有构造函数,toString、hasOwnProperty属性,所以如果需要的话,可以在数据结构中使用这些键,而不需要通过hasOwnProperty进行判断。


1、{} 和 new Object() 除了本身创建的对象,都继承了 Object 原型链上(Object.prototype)的属性或者方法,eg:toString();当创建的对象相同时,可以说 {} 等价于 new Object() 。

2、Object.create() 是将创建的对象继承到原型链上,而本身没有继承 Object.prototype 的属性和方法。

// 对象字面量创建的是对象,而构造函数创建的是函数对象

var a = {x:1, y:2} // 对象字面量

var b = new Object({x:1, y:2}) // 构造函数

var c = Object.create({x:1,y:2}) // 创建一个对象

var d = Object.create(null)

var f = Object.create(Object.prototype)

console.log(a) // {x: 1, y: 2}

console.log(b) // {x: 1, y: 2}

console.log(c, d, f) // {}

console.log(a.x, b.x, c.x) // 1 1 1

console.log(a.__proto__.x, b.__proto__.x, c.__proto__.x) // undefined undefined 1

// a、b、f 继承 Object.prototype 的属性或者方法

console.log(a.__proto__, b.__proto__, f.__proto__) // Object 原型链上(Object.prototype)的属性或者方法

// c 将创建的对象继承到原型链上,本身没有继承 Object.prototype 的属性和方法

console.log(c.__proto__) // {x: 1, y: 2}

// d 创建了一个空的对象,没有继承 Object.prototype 的属性和方法

console.log(d.__proto__) // undefined

console.log(a.__proto__.x === b.__proto__.x) // true

console.log(a.__proto__.x === c.__proto__.x) // false

console.log(a.__proto__ === b.__proto__) // true

console.log(a.__proto__ === c.__proto__) // false

console.log(a.__proto__ === f.__proto__) // true

console.log(d.__proto__ === f.__proto__) // false

console.log(a.__proto__ === Object.prototype) // true

console.log(b.__proto__ === Object.prototype) // true

console.log(c.__proto__ === Object.prototype) // false

console.log(d.__proto__ === Object.prototype) // false

console.log(f.__proto__ === Object.prototype) // true

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容