# Object.create
ES5通过增加Object.create()方法将原型式继承的概念规范化了。这个方法接受两个参数:作为新对象原型的对象,以及给新对象定义额外属性的对象
let person = {
name:'ff',
friends: ['hh']
}
let anotherPerson = Object.create(person)
console.log(anotherPerson.__proto__ == person) //true
let yetAnotherPerson = Object.create(person,{
name:{
value:'hh'
}
})
console.log(yetAnotherPerson.name) //hh
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
手写Object.create
function create(obj){
function F(){}
F.prototype = obj
return new F()
}
1
2
3
4
5
2
3
4
5
# new Object()
new Object()就是使用构造函数创建对象,new 运算符做了以下4件事情:
- 创建一个空的js对象
- 设置对象的constructor到另一个对象
- 将新创建的对象作为this上下文
- 如果该函数没有自己的返回对象则返回this
实现一个new的方法
//第一个参数是构造函数 之后的参数是给构造函数要传入的参数
function newFake(){
let obj = new Object();
//取出第一个参数即要传入的构造函数
const constructor = Array.prototype.shift.call(arguments) //通过call()让arguments能够执行shift方法
//obj可以访问到构造函数原型中的属性
obj.__proto__ = constructor.prototype
//将构造函数的this指向新建的对象 obj就可以访问构造函数中的属性
const result = constructor.apply(obj,arguments);
//返回类型判断,如果是对象 则返回构造函数返回的对象, 否则返回新创建的对象
reutrn typeof result === 'object' ? result : obj;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15