JS原型链总结:构造函数、实例、原型对象之间的关系
程序员文章站
2022-06-14 23:39:12
构造函数、实例、原型对象之间的关系
instanceof原理
检测对象的原型对象与构造函数的原型是否是同一个对象,如果不是,根据对象的原型链依次查找,直到相等,或者到达原型链顶端。
上面文字可能...
构造函数、实例、原型对象之间的关系
instanceof原理
检测对象的原型对象与构造函数的原型是否是同一个对象,如果不是,根据对象的原型链依次查找,直到相等,或者到达原型链顶端。
上面文字可能表达的不是很清楚,下面上代码:
function myinstanceof (obj, constructor) { // 对象的原型对象 let objproto = object.getprototypeof(obj); // 构造函数的原型对象 let constructorproto = constructor.prototype; if (objproto === constructorproto) { return true; } else { while (objproto = object.getprototypeof(objproto)) { if (objproto === constructorproto) { return true; } } return false; } } function person (name) { this.name = name; } person.prototype.hi = function () { console.log(`hi, my name is ${this.name}`); }; let p = new person('monkey'); p.hi(); console.log('------------------------------------------------'); let other = {name: 'lucy'}; console.log(`p is myinstanceof person : ${myinstanceof(p, person)}`); console.log(`p is myinstanceof object : ${myinstanceof(p, object)}`); console.log(`other is myinstanceof person : ${myinstanceof(other, person)}`); console.log(`other is myinstanceof object : ${myinstanceof(other, object)}`); console.log('------------------------------------------------'); console.log(`p is instanceof person : ${myinstanceof(p, person)}`); console.log(`p is instanceof object : ${myinstanceof(p, object)}`); console.log(`other is instanceof person : ${myinstanceof(other, person)}`); console.log(`other is instanceof object : ${myinstanceof(other, object)}`);
使用myinstanceof和instanceof的结果是一致的