Object.create()

方法创建一个新对象,使用现有的对象来提供新创建的对象的proto

用法

1
2
3
4
5
6
7
8
9
10
11
12
var parent = {
name:'parent',
sayHi:function(){
console.log(this.name)
return this
}
}
var son = Object.create(parent)
console.log(son.__proto__ === parent)
son.sayHi()//'parent'
son.name = 'son'
son.sayHi() //'son'
1
2
3
4
5
function myCreate(obj) {
function F(){}
F.prototype = obj
return new F()
}

instanceof

instanceof运算符用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链

用法

1
2
3
4
5
6
7
8
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
const auto = new Car('Honda', 'Accord', 1998);
console.log(auto instanceof Car);//true
console.log(auto instanceof Object);// true

手写实现

1
2
3
4
5
6
7
8
9
10
11
12
13
function myInstanceof(a,b) {
//如果是基本数据类型返回false
if (typeof a !== 'object' || b === null) {
return false;
}
let proto = a.__proto__
//开始查找
while(proto){
if(proto === null) return false //没找到
if(proto === b.prototype) return true //找到了
proto = proto.__proto__ //迭代
}
}