区别
Object.create
创建的新函数并没有继承构造函数的属性和方法,只继承了原型方法和原型属性
new
在实现 Object.create 的基础上,继承了原对象的属性和方法
var Base=function(){
this.a = 2
this.b = 4
}
Base.prototype.c = 3;
var o1= new Base();
var o2 = Object.create(Base);
console.log(o1.a);
console.log(o2.a);//那这样创建有什么用呢
打印调试结果
再直观一点:
代码实现
Object.create
function createObject(object){
function F(){};
F.prototype = object;
return new F();
}
const person= {
name:'willim',
}
const p1 = createObject(person);
console.log(p1.name);
new
function newFunction() {
let res = {};
let construct = Array.prototype.shift.call(arguments);
//对象的原型 赋值
res.__proto__ = construct.prototype;
let turn = construct.apply(res, arguments);
//返回对象
return turn instanceof Object ? turn : res;
}
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.sayHi = function () {
console.log(this.name);
}
var person1 = newFunction(Person, 'xm', 18);
console.log(person1.age);
person1.sayHi();