Apa itu instance di javascript?

In this article, I am going to discuss Object Instances in JavaScript with Examples. This is a continuation part to our previous article, so, please read our previous article where we discussed Object Constructors in JavaScript.

Understanding Object Instances

We just can’t look at a JavaScript object and identify that it is an object of a specific type, like a dog or a car. In JavaScript, objects are dynamic structures, and the type of all objects is “object” only, no matter what properties and methods it has. But we can get some information about an object if we know about the constructor that created the object.

Remember that each time we call a constructor using the new operator, we are creating a new instance of an object. And, if we used, say, the Car constructor to do that, then we say, informally, that the object is a car. More formally, we say that an object is an instance of a Car.

Apa itu instance di javascript?

As we know, each instance can have its own unique set of property values, but we think of all the objects created from the Car constructor as instances of Car. We can think of these cars as being the same kind of object because they all were created by the same constructor.

Now saying an object is an instance of some constructor is more than talk. We can actually write code to check the constructor that made an object with the instanceof operator. Let’s look at some code:

Apa itu instance di javascript?

As it proves that, one of the things the new operator does behind the scenes when the object is created is to store information that allows it to determine, at any time, the constructor that created the object. And instanceof uses that to determine if an object is an instance of a certain constructor or not. What we discussed above is given in the below example.

Example: Object’s creation in JavaScript, by Using Object constructor to check object instances of constructor
<html>
<head>
    <title>Object's creation in JavaScript, by Using Object constructor to check object instances of constructor example</title>
</head>
<body>
    <script>
        //Car constructor
        function Car(params) {
            this.make = params.make;
            this.model = params.model;
            this.year = params.year;
            this.color = params.color;
            this.passengers = params.passengers;
            this.convertible = params.convertible;
            this.mileage = params.mileage;
            this.started = false;
            this.start = function () {
                this.started = true;
            };
            this.stop = function () {
                this.started = false;
            };
            this.drive = function () {
                if (this.started) {
                    alert("Zoom zoom!");
                } else {
                    alert("You need to start the engine first.");
                }
            };
        }

        //object literals
        var cadiParams = {
            make: "GM", model: "Cadillac", year: 1955, color: "tan",
            passengers: 5, convertible: false, mileage: 12892
        };
        var cadi = new Car(cadiParams); //calling constructor

        //instanceof operator
        if (cadi instanceof Car) {
            console.log("cadi is an instance of Car, it's a Car!");
        };
    </script>
</body>
</html>

Now run the above code, open the browser developer tool by pressing the F12 key and have a look at the Console tab and you should see the following message in the Console.

Apa itu instance di javascript?

Example: Object’s creation in JavaScript, by Using Object constructor to check object instances of dog and cat constructor
<html>
<head>
    <title>Object's creation in JavaScript, by Using Object constructor to check object instances of dog and cat constructor example</title>
</head>
<body>
    <script>
        //Sample code1 of Dog
        //Dog constructor
        function Dog(name, breed, weight) {
            this.name = name;
            this.breed = breed;
            this.weight = weight;
            this.bark = function () {
                if (this.weight > 25) {
                    alert(this.name + " says Woof!");
                } else {
                    alert(this.name + " says Yip!");
                }
            };
        }

        // code here to implement the dogCatcher function to test if its an instance of Dog or not.
        function dogCatcher(obj) {
            //instanceof operator
            if (obj instanceof Dog) {
                return true;
            };
        }

        var fido = { name: "Fido", breed: "Mixed", weight: 38 }; //Object literal
        var fluffy = new Dog("Fluffy", "Poodle", 30); //calling dog constructor
        var spot = new Dog("Spot", "Chihuahua", 10);
        var dogs = [meow, whiskers, fido, fluffy, spot];
        console.log('=====Sample code1 of dog=====');
        for (var i = 0; i < dogs.length; i++) {
            if (dogCatcher(dogs[i])) {
                console.log(dogs[i].name + " is a dog!");
            }
        }

        //Sample code2 of Cat
        //Cat Constructor
        function Cat(name, breed, weight) {
            this.name = name;
            this.breed = breed;
            this.weight = weight;
        }

        // code here to implement the catCatcher function to test if it’s an instance of Cat or not.
        function catCatcher(obj) {
            //instanceof operator
            if (obj instanceof Cat) {
                return true;
            };
        }
        var meow = new Cat("Meow", "Siamese", 10);
        var whiskers = new Cat("Whiskers", "Mixed", 12);
        var cats = [meow, whiskers, fido, fluffy];
        console.log('=====Sample code2 of Cat=====');
        for (var i = 0; i < cats.length; i++) {
            if (catCatcher(cats[i])) {
                console.log(cats[i].name + " is a cat!");
            }
        }

    </script>
</body>
</html>

Run the above code, open the browser developer tool by pressing the F12 key and have a look at the Console tab and you should see the following messages in the Console.

Apa itu instance di javascript?

So, an object is a dog if it was created with a Dog constructor, -and not otherwise? Yes, that’s how it works. JavaScript doesn’t have a strong sense of an object’s type, so if we need to compare objects to see if they are both cats or both dogs, we check to see if they were constructed the same way—that is, with the same constructor function. As we have said, a cat is a cat if it was created by the Cat constructor, and a dog is a dog if it was created by the Dog constructor.

Objects can have their own independent properties even constructed object too

We have talked a lot about how to use constructors to create consistent objects—objects that have the same set of properties and the same methods. But what we haven’t mentioned is that using constructors still doesn’t prevent us from changing an object into something else later, because after an object has been created by a constructor, it can be altered. As we know that Properties and methods can change at any time

What exactly are we talking about? If we remember when we introduced object literals? We looked at how we could add properties after the object was created. we can do the same with objects created from constructors.

var fido = new Dog("Fido", "Mixed", 38); // dog constructor
fido.owner = "Bob";  //adding new property
delete fido.weight; //deleting a property using delete operator

Here’s our dog Fido is created with the Dog constructor. We can add a new property just by assigning it a value in our object. Or we can get rid of/remove a property by using the delete operator. We can even add new methods if we like:

fido.trust = function (person) { //anonymous function
            return (person === "Bob");
};

To add a method just assign the method to a new property name in the object using assignment operator i.e.: =, They are added like Anonymous function See, they are everywhere in an object when assigning the method to it.

Notice that here we’re changing only the fido object. If we add a method to fido, only fido has that method. No other dogs have it:

var notBite = fido.trust(“Bob”); This line of code works because trust is defined previously in the fido object. So notBite is true.

var spot = new Dog(“Spot”, “Chihuahua”, 10);
var notBite1 = spot.trust(“Bob”);
This code doesn’t work because the spot object doesn’t have a method trust assign to it, calling it to result in: “TypeError: Object #<Dog> has no method ‘trust'”

So, if I change a car object after I create it, is it still a car?

Yes, a car is still a car, even if we change it later. And what we mean by that is if we check to see if our object is still an instance of Car, it will be. For instance, if we create a car object:

var cadiParams = { make: "GM", model: "Cadillac",
                    year: 1955, color: "tan",
       	            passengers: 5, 
                    convertible: false,
                    mileage: 12892
};
var cadi = new Car(cadiParams);

We can add a new property chrome to it and delete the property convertible from the cadi object:

cadi.chrome = true;
delete cadi.convertible;

and yet, the cadi is still a car:

cadi instanceof Car;// Evaluate to be true

Now is it really a car in practical terms? What if we deleted all the property in the object? Would it still be a car? The instanceof operator would tell us yes. But judging by our own terms, probably not. This is what we meant earlier when we said that JavaScript has a dynamic type system. What we discussed above is given in the below example.

Example: Object’s creation in JavaScript, by Using Object constructor to check constructed objects can have their own independent properties
<html>
<head>
    <title>Object's creation in JavaScript, by Using Object constructor to check constructed objects can have their own independent properties example</title>
</head>
<body>
    <script>
        //Sample code1 of Dog
        //Dog constructor
        function Dog(name, breed, weight) {
            this.name = name;
            this.breed = breed;
            this.weight = weight;
            this.bark = function () {
                if (this.weight > 25) {
                    alert(this.name + " says Woof!");
                } else {
                    alert(this.name + " says Yip!");
                }
            };
        }

        var fido = new Dog("Fido", "Mixed", 38); //Fido instance of Dog type
        fido.owner = "Bob"; //new property added
        delete fido.weight; //deleted the weight property

        fido.trust = function (person) {  //added a method just assign the method to a new property name in the object.
            return (person === "Bob");
        };
        var notBite = fido.trust("Bob");
        console.log('=====Sample code1 of Dog=====');
        console.log('Fido object after adding new and deleting existing property: ', fido);
        console.log("Is trust a property of fido object: ", notBite);

        var spot = new Dog("Spot", "Chihuahua", 10); //spot instance of Dog type
        var notBite1 = spot.trust("Bob");  // method is not added to spot hence throws an error Uncaught TypeError: spot.trust is not a function
        console.log('spot object: ', spot);
        console.log("Is trust a property of spot object: ", notBite1);

        console.log("type of Dog: ", typeof Dog) //function
        console.log("type of fido: ", typeof fido) //object
        console.log("type of spot: ", typeof spot) //object
        console.log("Is fido an instance of a Dog: ", fido instanceof Dog); //true
        console.log("Is spot an instance of a Dog: ", spot instanceof Dog); //true

        //Sample code2 of Car
        //Car constructor
        function Car(params) {
            this.make = params.make;
            this.model = params.model;
            this.year = params.year;
            this.color = params.color;
            this.passengers = params.passengers;
            this.convertible = params.convertible;
            this.mileage = params.mileage;
            this.started = false;
            this.start = function () {
                this.started = true;
            };
            this.stop = function () {
                this.started = false;
            };
            this.drive = function () {
                if (this.started) {
                    alert("Zoom zoom!");
                } else {
                    alert("You need to start the engine first.");
                }
            };
        }

        //object literal
        var cadiParams = {
            make: "GM", model: "Cadillac",
            year: 1955, color: "tan",
            passengers: 5, convertible: false,
            mileage: 12892
        };
        var cadi = new Car(cadiParams); //call to Car constructor

        cadi.chrome = true; //new property added
        delete cadi.convertible; //deleted the convertible property
        console.log('=====Sample code2 of Car=====');
        console.log('cadi object after adding new and deleting existing property: ', cadi);

        console.log("type of Car: ", typeof Car) //function
        console.log("type of cadi: ", typeof cadi) //object
        console.log("Is cadi an instance of a Car: ", cadi instanceof Car); //true

    </script>
</body>
</html>

Output: When calling the unassigned method i.e. spot.trust(“Bob”); we will get the following error in the console tab.

Apa itu instance di javascript?

Now the unassigned method i.e. spot.trust(“Bob”); as shown in the below example.

<html>
<head>
    <title>Object's creation in JavaScript, by Using Object constructor to check constructed objects can have their own independent properties example</title>
</head>
<body>
    <script>
        //Sample code1 of Dog
        //Dog constructor
        function Dog(name, breed, weight) {
            this.name = name;
            this.breed = breed;
            this.weight = weight;
            this.bark = function () {
                if (this.weight > 25) {
                    alert(this.name + " says Woof!");
                } else {
                    alert(this.name + " says Yip!");
                }
            };
        }

        var fido = new Dog("Fido", "Mixed", 38); //Fido instance of Dog type
        fido.owner = "Bob"; //new property added
        delete fido.weight; //deleted the weight property

        fido.trust = function (person) {  //added a method just assign the method to a new property name in the object.
            return (person === "Bob");
        };
        var notBite = fido.trust("Bob");
        console.log('=====Sample code1 of Dog=====');
        console.log('Fido object after adding new and deleting existing property: ', fido);
        console.log("Is trust a property of fido object: ", notBite);

        var spot = new Dog("Spot", "Chihuahua", 10); //spot instance of Dog type
        //var notBite1 = spot.trust("Bob");  // method is not added to spot hence throws an error Uncaught TypeError: spot.trust is not a function
        console.log('spot object: ', spot);
        //console.log("Is trust a property of spot object: ", notBite1);

        console.log("type of Dog: ", typeof Dog) //function
        console.log("type of fido: ", typeof fido) //object
        console.log("type of spot: ", typeof spot) //object
        console.log("Is fido an instance of a Dog: ", fido instanceof Dog); //true
        console.log("Is spot an instance of a Dog: ", spot instanceof Dog); //true

        //Sample code2 of Car
        //Car constructor
        function Car(params) {
            this.make = params.make;
            this.model = params.model;
            this.year = params.year;
            this.color = params.color;
            this.passengers = params.passengers;
            this.convertible = params.convertible;
            this.mileage = params.mileage;
            this.started = false;
            this.start = function () {
                this.started = true;
            };
            this.stop = function () {
                this.started = false;
            };
            this.drive = function () {
                if (this.started) {
                    alert("Zoom zoom!");
                } else {
                    alert("You need to start the engine first.");
                }
            };
        }

        //object literal
        var cadiParams = {
            make: "GM", model: "Cadillac",
            year: 1955, color: "tan",
            passengers: 5, convertible: false,
            mileage: 12892
        };
        var cadi = new Car(cadiParams); //call to Car constructor

        cadi.chrome = true; //new property added
        delete cadi.convertible; //deleted the convertible property
        console.log('=====Sample code2 of Car=====');
        console.log('cadi object after adding new and deleting existing property: ', cadi);

        console.log("type of Car: ", typeof Car) //function
        console.log("type of cadi: ", typeof cadi) //object
        console.log("Is cadi an instance of a Car: ", cadi instanceof Car); //true

    </script>
</body>
</html>

Now run the above code and you should get the following messages in the Console tab.

Apa itu instance di javascript?

In the next article, I am going to discuss Real-World Constructors in JavaScript with Examples. Here, in this article, I try to explain Object Instances in JavaScript with Examples and I hope you enjoy this Object Instances in JavaScript article.