标题new Object() 和 Object.creat() 的区别
共同点
两者都是创建对象的方式
不同点
1.创建空对象的不同
1.1 new Object(null),创建的是空对象,在该对象上有继承原型链的方法和属性;
1.2 Object.creat(null),创建的是空对象,在该对象上没有继承原型链的方法和属性;
如图:上面的是1.1new Object(null),对象上面存在属性和方法;下面的是1.2 Object.creat(null),对象和原型链上不存在属性和方法;
//方式一:通过new方法来创建实例
var person1 = new Person(null);
//方式二:通过.creat方法来创建示例
var person2 = Object.create(null)
console.log(person1);
console.log(person2)
2. 创建实例的区别
2.1 使用 new Person() 来创建Person构造函数的新实例,
2.2 使用 Object.create(Person.prototype) 来创建Person构造函数的新实例,
//Person构造函数
function Person(){
}
//示例
//方式一:通过new方法来创建实例
var person1 = new Person();
//方式二:通过.creat方法来创建示例
var person2 = Object.create(Person.prototype)
console.log(person1);
console.log(person2);
结果:
采用new Object(Person) 和 new Object(Person.prototype)的区别 (上面是Person,下面是Person.prototype)
var person2 = Object.create(Person)
var person3 = Object.create(Person.prototype)
console.log('person2 instanceof Person:',person2 instanceof Person);
console.log('person3 instanceof Person:',person3 instanceof Person);
结果:
结果显示 Object.create(Person)创建的对象不属于Person原型链,而通过Object.create(Person.prototype)创建的对象属于Person原型链。
所以要想通过Object.create()创建具有原型链的对象应该用Object.create(Object.prototype)