Stories

Detail Return Return

Function instanceof Object和Object instanceof Function都true - Stories Detail

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

image.png

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 //true

5、特例

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

image.png

user avatar dingtongya Avatar littlelyon Avatar zourongle Avatar linx Avatar u_17443142 Avatar shuirong1997 Avatar xiaolei_599661330c0cb Avatar assassin Avatar hyfhao Avatar congjunhua Avatar heath_learning Avatar sy_records Avatar
Favorites 32 users favorite the story!
Favorites

Add a new Comments

Some HTML is okay.