0

I want to know why there is difference between the outputs of the following classes.

I have tried following code to get the class values in console. For one particular case(the last console) I am wondering how this is returning this value.

let rectangle = class{
    constructor(name,num){
        this.name =name;
        this.num =  num;
    }
}

let rect =  new rectangle();
console.log("bantai",rect);
//output: rectangle { name: undefined, num: undefined }


let rectangle3 = class rectangle2{
    constructor(model, version){
        this.model = model;
        this.version = version;
    }
}
var abh =  new rectangle3();

console.log(abh);
//output:rectangle2 { model: undefined, version: undefined }

console.log(rectangle3);
//output:[Function: rectangle2]

I am wondering about the last console console.log(rectangle3) value why it is returning this value as array with one element ie [Function: rectangle2]

4

3 回答 3

2

为什么它将此值作为具有一个元素的数组返回,即 [Function: rectangle2] ?

那不是数组。它就是 JavaScript 中的对象是如何被记录的:

 console.log(
   {}, // [Object object]
   new Map, // [Object Map]
   function() {}, // [Function]
 );
于 2019-01-17T15:20:17.117 回答
1

为什么它将此值作为具有一个元素的数组返回,即[Function: rectangle2]

它不记录数组,只是您使用的任何环境的奇怪控制台格式。这些都不是有效的 JS 语法,不要指望括号引用数组。您可以尝试记录包含函数的实际数组并比较输出。

于 2019-01-17T15:47:08.510 回答
0

在最后一个中,您正在记录该函数,但您没有调用它。在引擎盖下,类只是函数。当您调用一个时,它会创建该类的一个实例;如果您引用一个而不调用它,那么您引用的是函数,而不是实例。考虑以下类似的示例:

function doSomething() {
    return 4;
}
console.log(doSomething()); // Says 4
console.log(doSomething); // Says it's a function
于 2019-01-17T14:58:55.457 回答