What is the difference between Object() and newObject()?

Asked 2 years ago, Updated 2 years ago, 27 views

I understand that Object() is a constructor function and creates an instance with the new keyword.

By the way, even if you call the Object() constructor function directly, it seems to have the same result as using newObject(). Is there a difference between what looks like and the other two?

(Except for some idiot using the identifier Object to override the constructor function)

javascript

2022-09-22 21:11

1 Answers

It is true that Object() calls the constructor and adds a new to create an instance. However, if the constructor treats you like Object2 in the following example, you can create an instance by calling Object2().

function Object1 () {
    //this.color = "red";
}

function Object2(){
   if (!(this instanceof Object2)){
        return new Object2();
   }
}

var object1WithNew = new Object1();
var object1WithoutNew = Object1();
console.log("object1WithNew: "+object1WithNew);
console.log("object1WithoutNew: "+object1WithoutNew);

var object2WithNew = new Object2();
var object2WithoutNew = Object2();
console.log("object2WithNew: "+object2WithNew);
console.log("object2WithoutNew: "+object2WithoutNew);

When executing the above code, Object1 is not created as Object1(), which is not handled separately by the constructor, but Object2 is created by calling Object2() only and output as follows.

object1WithNew: [object Object]
object1WithoutNew: undefined
object2WithNew: [object Object]
object2WithoutNew: [object Object]

It seems that the object is also being processed separately by the constructor. For reference, Object is

You can create an instance in three ways:


2022-09-22 21:11

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.