簡體   English   中英

為什么 typeof Array 返回“函數”而 typeof [數組變量] 返回“對象”?

[英]Why does typeof Array returns “function” and typeof [array variable] returns an “Object”?

我有機會遇到這個問題,但無法找到答案。

var arr = [];

為什么typeof Array返回"function"typeof arr返回"Object"

誰能解釋一下。

當您編寫typeof Array時,這意味着您正在獲取構造函數 function 的類型。 由於class在引擎蓋下是構造函數 function。 讓我舉個例子:

class Person {
    constructor(firstName, lastName, address) {
        this.firstName= firstName;
        this.lastName = lastName;
        this.address= address;
    }

    getFullName () {
        return this.firstName + " " + this.lastName ;
    }
}

並創建 class 的實例:

let car = new Person ("Jon", "Freeman", "New York");

在上面的代碼中,我們創建了一個變量car ,它引用了 class 中定義的 function 構造函數:

function Person (firstName, lastName, address) {
        this.firstName = firstName,
        this.lastName = lastName,
        this.address = address,
        this.getFullName = function () {
            return this.firstName+ " " + this.lastName;
        }
}

所以這就是typeof Array返回function的原因。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM