创建一个对象
1. 字面量生成
var foo = {};
2. Object.create()
Objec.create 创建一个新对象, 使用现有对象作为新对象的原型( prototype )
const bar = {};
const foo = Object.create(bar);
foo.__proto__ === bar; // true
3. new
new 创建一个用户定义的对象类型的实例或具有构造函数的内置对象的实例
- new 创建一个对象, 这个新对象指向构造函数的原型
- 新创建对象实现了构造函数的方法
- 如果构造函数有返回值且是对象, 则返回这个对象, 否则返回新创建的对象
funtion Parent(){}
Parent.prototype.foo=function(){};
const child = new Parent();
// child 的构造函数是 parent
child.constructor === Parent; // true
//创建的对象( child )通过 __proto__ 指向构造函数的原型
child.__proto__ === Parent.prototype; // true
//构造函数上的 prototype 中存在 constructor 函数就是构造函数本身
Parent.prototype.constructor === Parent; //true
Object.create 和 new 互相实现
//前置
function Parent (name){ this.name=name};
Parent.prototype.getName=function(){
console.log(name);
};
使用 Object.create 实现 new
function newFun (parent){
const newObj = Object.create(parent.prototype);
const result = parent.apply(newObj,Array.prototype.slice.call(arguments,1));
return result && typeof result === 'object' ? result : newObj;
}
const child = newFun(Parent, 'zz');
使用 new 实现 Object.create
function inherit (p){
function f(){};
f.prototype = p;
return new f();
}
const child= inherit(Parent.prototype);
继承 / 原型链
function Person(name,age){
this.name=name;
this.age=age;
}
Person.prototype.getInfo=function(){
console.log({
name: this.name || 'zz',
age: this.age || 1,
hobbiles: this.hobbies && this.hobbies.length > 0 ? this.hobbies : ['eat','sleep']
});
}
function Child(hobbies){
this.hobbies=hobbies;
//继承构造函数
Person.apply(this,Array.prototype.slice.call(arguments,1));
}
function inherit(p){
if(Object.create){
return Object.create(p);
}
function f(){};
f.prototype = p;
return new f();
}
//继承原型
Child.prototype = inherit(Person.prototype);
const xiaoming= new Child(['swing','ball'],'小明','5');
xiaoming.getInfo()
//原型链 xiaoming.__proto__.__proto__ === Child.prototype.__proto__ === Parent.prototype