简体   繁体   中英

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

I had a chance to met this question but unable to find an answer.

var arr = [];

Why does typeof Array returns "function" and typeof arr returns an "Object" ?

Can anyone explain please.

When you write typeof Array , it means that you are getting type of constructor function. As class is under the hood is constructor function. Let me show an example:

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

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

and to create an instance of the class:

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

In the above code, we've created a variable car which references to function construtor defined in the class:

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

So this is a reason why typeof Array returns function .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM