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]

3 Answers3

2

why it is returning this value as array with one element ie [Function: rectangle2] ?

Thats not an array. Its just how Objects in JavaScript get logged:

 console.log(
   {}, // [Object object]
   new Map, // [Object Map]
   function() {}, // [Function]
 );
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
1

Why it is returning this value as array with one element ie [Function: rectangle2]

It does not log an array, it's just weird console formatting of whatever environment you are using. None of this is valid JS syntax, don't expect the brackets to refer to an array. You can try to log an actual array containing a function and compare the output.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
0

In the last one, you're logging the function, but you're not calling it. Under the hood, classes are just functions. When you call one, it creates an instance of that class; if you reference one without calling it, then you're referencing the function, not an instance. Consider the following similar example:

function doSomething() {
    return 4;
}
console.log(doSomething()); // Says 4
console.log(doSomething); // Says it's a function
IceMetalPunk
  • 5,476
  • 3
  • 19
  • 26