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() son.name = 'son' son.sayHi()
|
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); console.log(auto instanceof Object);
|
手写实现
1 2 3 4 5 6 7 8 9 10 11 12 13
| function myInstanceof(a,b) { 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__ } }
|