Function instanceof Object和Object instanceof Function都true
文章目录
1、需求
在看原型链。没想明白Function和Object的关系。就查了下。
2、原则
js之父在设计js原型、原型链的时候遵从以下两个准则:
- 准则1:原型对象(即Person.prototype)的constructor指向构造函数本身
- 准则2:实例(即person)的__proto__和原型对象指向同一个地方
3、关系
null-> Object.prototype -> Function.prototype->Function->Object
首先:js中先创建的是Object.prototype这个原型对象。
然后:在这个原型对象的基础之上创建了Function.prototype这个原型对象。
其次:通过这个原型对象创建出来Function这个函数。
最后: 又通过Function这个函数创建出来之后,Object()这个对象。
4、Demo

Object.__proto__ === Function.prototype // true Object()是一个构造函数,函数也是一个对象
// Object 是由Function 生成的
Object instanceof Function === true // true
Function.prototype.__proto__ === Object.prototype // true
//Function.prototype 是由 Object.prototype生成的
Object.prototype.constructor===Object // true
Object instanceof Object === true // true
//Object.prototype===Object.prototype
Function.__proto__ === Function.prototype // true Function()是一个构造函数,构造了函数本身
//Function 是由 Function.prototype 生成的
Function.prototype.constructor===Function // Function原型对象的constructor 指向Function本身
Function instanceof Function === true // true
//Function.prototype===Function.prototype
//Function.__proto__ === Object.prototype //false
Function instanceof Object === true // true
Object.prototype.__proto__ === null //true
Object.__proto__ === Object.prototype //false,因为已经指向了Function的原型对象
Function.prototype.constructor===Function //true5、特例
Function instanceof Object === true // true
Object instanceof Function === true // true原因是:instanceof 运算符用来检测 constructor.prototype 是否存在于参数 object 的原型链上。
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);
// expected output: true
console.log(auto instanceof Object);
// expected output: true

评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论