Thursday, 30 August 2018

JavaScript: instanceof : Check the class

‘instanceof’ operator is used to tests whether an object has in its prototype chain the prototype property of a constructor.

Syntax
object instanceof constructor

instanceof.html
<!DOCTYPE html>

<html>

<head>
    <title>instanceof operator Example</title>
</head>

<body>
    <script>
        function A() {

        }

        function B() {

        }

        function C() {

        }

        // Apply prototype inheritance
        C.prototype = new B();

        var obj = new C(); // obj is instance for both B and C

        document.write("(obj instanceof A) : " + (obj instanceof A) + "<br />");
        document.write("(obj instanceof B) : " + (obj instanceof B) + "<br />");
        document.write("(obj instanceof C) : " + (obj instanceof C) + "<br />");
    </script>
</body>

</html>

Load above page in browser, you can able to see following text.

(obj instanceof A) : false
(obj instanceof B) : true
(obj instanceof C) : true



Previous                                                 Next                                                 Home

No comments:

Post a Comment