What is the functionality of the "instanceof" operator in JavaScript?

When looking at the code provided, it can be seen that both checks of obj2 and obj3 at the end using instanceof return true even though they were constructed differently and have different results when returning the name property.

var Obj1 = function() {
    this.name = "foo1";
};
Obj1.prototype.name = "foo1onProt";
var obj1 = new Obj1();

var Obj2 = function() {};
Obj2.prototype = new Obj1();
Obj2.prototype.constructor = Obj2;
var obj2 = new Obj2();

var Obj3 = function() {};
Obj3.prototype = Object.create(Obj1.prototype);
Obj3.prototype.constructor = Obj3;
var obj3 = new Obj3();

console.dir(obj1);
console.log("obj1.name: " + obj1.name);

console.dir(obj2);
console.log("obj2.name: " + obj2.name);

console.dir(obj3);
console.log("obj3.name: " + obj3.name);

console.log("obj2 instanceof Obj1: " + (obj2 instanceof Obj1));
console.log("obj3 instanceof Obj1: " + (obj3 instanceof Obj1));

Result of running the code in Chrome:

Obj1
  name: "foo1"
  __proto__: Object
    constructor: function () {
    name: "foo1onProt"
    __proto__: Object
obj1.name: foo1
Obj2
  __proto__: Obj1
    constructor: function () {}
    name: "foo1"
    __proto__: Object
      constructor: function () {
      name: "foo1onProt"
      __proto__: Object
obj2.name: foo1
Obj3
   __proto__: Object
   constructor: function () {}
   __proto__: Object
     constructor: function () {
     name: "foo1onProt"
     __proto__: Object
obj3.name: foo1onProt

obj2 instanceof Obj1: true
obj3 instanceof Obj1: true

To distinguish between obj2 and obj3, what is the most effective approach? How does the instanceof operator actually work?

Answer №1

What is the most effective way to distinguish between obj2 and obj3?

The method for distinguishing between obj2 and obj3 will vary based on the specific context in which they are being used. One approach could involve utilizing instanceof Obj2 and instanceof Obj3. Given that both objects have been constructed with Obj1.prototype in their prototype chain, it follows that they would be recognized as instances of what we would refer to as the superclass in a class-based OOP system.

How does the instanceof operator actually function?

A concise explanation

obj instanceof F checks whether the object referenced by F.prototype exists anywhere within the prototype chain of obj. It does not rely on the constructor property at all.

Further details

This behavior is specified in §11.8.5 - The instanceof Operator, which indicates (indirectly, through §8.6.2) that it invokes the [[HasInstance]] internal method of the function object, supplying the object under examination. Function's [[HasInstance]] (in §15.3.5.3) retrieves the object reference from the function's prototype property and then returns true if that object appears anywhere in the target object's prototype chain, or false otherwise.

The usage of constructor is omitted because no part of JavaScript utilizes it — this is due to an object's constructor property being able to reference only one function, whereas an object can potentially be an instance of multiple functions. In situations involving pseudo-classical inheritance:

function F1() {}

function F2() {
  F1.call(this);
}
F2.prototype = Object.create(F1.prototype);
F2.prototype.constructor = F2;

var obj = new F2();
console.log(obj instanceof F1); // true
console.log(obj instanceof F2); // true

Both evaluations return true since the objects indicated by F1.prototype and F2.prototype are present within the prototype chain of obj.

A truthful instanceof outcome does not necessarily imply that obj was instantiated via a call to F, either directly or indirectly; it merely suggests an abstract association between them (F.prototype refers to an object found within obj's prototype chain). This connection typically indicates involvement of F in generating the object, though there is no guarantee.

For example:

function F() {}
var obj = Object.create(F.prototype);
console.log(obj instanceof F); // true

Note that F was not utilized in creating the object whatsoever.


To provide additional clarity and/or emphasis:

function F() {}
var p = {};
var obj = Object.create(p);
console.log(obj instanceof F); // false
F.prototype = p;
console.log(obj instanceof F); // true


An uncommon yet valid scenario involves:

function F1() {}
function F2() {}
F1.prototype = F2.prototype = {};
var obj = new F1();
console.log(obj instanceof F2); // true


Alternatively, consider:

function F1() {}
function F2() {}
var obj = new F2();
console.log(obj instanceof F1); // false
F1.prototype = F2.prototype;
console.log(obj instanceof F1); // true

Answer №2

In simpler terms: obj instanceof constructor returns true if obj has the same prototype as constructor in its inheritance chain. Essentially, you are asking whether obj can be treated as an instance of constructor or if it behaves like a constructor object.

There are various ways to include constructor's prototype in the chain of obj. Any of these methods will result in obj instanceof constructor evaluating to true. In the provided examples, both obj2 and obj3 have Obj1 in their prototype chain.

Therefore, when querying whether either obj2 or obj3 act as instances of Obj1, JavaScript assumes the answer is true by default—unless there have been alterations to the behavior of Obj1 at a later stage.

Answer №3

function Parent() {}

function Child() {
  Parent.call(this);
}
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;

var instance = new Child();
console.log(instance instanceof Parent); // true
console.log(instance instanceof Child); // true

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to rejuvenate an angular component

I am in the process of developing a mobile application using ionic 4. The app supports two languages, namely ar and en. The menu drawer is a pre-built component included within the app. In order to ensure that the drawer component displays the correct sty ...

Converting an array of object keys into integers only can be done using JavaScript

Here is an array of objects with various nutrients and their values: [ {nutrient: "Energy", per100: "449kcal", per35: "157kcal", id: 6} {nutrient: "Fat", per100: "24.4g", per35: "8.6g", id: 1} {nutrient: "Saturated fat", per100: "4.5g", per35: "1.6g ...

This route does not allow the use of the POST method. Only the GET and HEAD methods are supported. This limitation is specific to Laravel

I am encountering an issue while attempting to submit an image via Ajax, receiving the following error message: The POST method is not supported for this route. Supported methods: GET, HEAD. Here is the Javascript code: $("form[name='submitProfi ...

What are the steps to creating a duplicate of JotForm?

After exploring JotForm, I discovered it is an extremely interactive form builder utilizing the Prototype JS library. I am curious to know which JS framework or library would be a solid foundation for creating a similar form builder - JQuery, Prototype, ...

What exactly does the context parameter represent in the createEmbeddedView() method in Angular?

I am curious about the role of the context parameter in the createEmbeddedView() method within Angular. The official Angular documentation does not provide clear information on this aspect. For instance, I came across a piece of code where the developer i ...

Typescript throws an error indicating that the "this" object in Vue methods may be undefined, displaying error code TS2532

As a beginner in question writing, I apologize if my wording is not clear. The issue at hand: I am working on a Vue application with TypeScript. export default { methods: { setProgram: (program: Program)=>{ this.program = progra ...

When using $http in AngularJS, an error may occur when it

I ran a test on my PHP code independently and obtained the following output: {"tabId":1,"tabName":"Main","uId":"1"}{"tabId":2,"tabName":"Photography","uId":"1"} However, my AngularJS application is unable to receive the callback and is throwing an error ...

Sending data with an AJAX post request from JavaScript to a Python backend

Attempting to pass a dictionary from JavaScript to a Python script using AJAX POST method. Here's the JavaScript code: function foo(){ context = { 'var1': val1, 'var2': val2 } $.ajax({ ...

Swap two frames effortlessly with just a single click!

Is there a way to effortlessly change the contents of two frames with just one click? With a single click, I'd like to modify both "framename" and "framename2" by setting their href attribute to 'qwerty' and 'qwerty2' respectively ...

Is there a way to verify the presence of multiple array indices in React with TypeScript?

const checkInstruction = (index) => { if(inputData.info[index].instruction){ return ( <Text ref={instructionContainerRef} dangerouslySetInnerHTML={{ __html: replaceTextLinks(inputData.info[index].instruction) ...

Updating the legend boxes of a chart in Chart Js to match the style of the graph lines

I need assistance updating the legend boxes of my graphs with graph line style. https://i.sstatic.net/zhi4L.pngActual Consumption https://i.sstatic.net/dAjlp.png Average Use https://i.sstatic.net/YMC7I.png Here is the code snippet I am currently using, ...

Having trouble getting the Random Function to function correctly in Discord.js

I'm working on a piece of code that generates a random value to select two different values from two separate arrays. Every time I run it, however, the result seems to be the same and not truly random. I'm not sure where I went wrong with this. I ...

I'm having trouble getting the function inside onLoad to run in my Next.js project - can anyone help

While I was exploring nextjs.org and following the tutorial, I encountered an issue where the function inside onLoad wasn't executing. It's puzzling because there was no call made to that link in the networks tab of my browser's developer to ...

Monitoring the initiation and completion of web requests within the Ionic framework

Currently utilizing the ionic framework in conjunction with Angular JS. In need of assistance on how to monitor the initiation of a web request. To handle the completion of a request, I have created a directive with an onLoad attribute. Here is the exam ...

If the first <select> option is chosen, then a second <select> validation is necessary

Is it possible to make the second selection required for validation only if the 'yes' option is selected in the first one? <div class="form-group" ng-class="{ 'has-error' : articleEditForm.pnp.$invalid && !articleEditForm.pn ...

When Google Chrome encounters two variables or functions with the same name, how does it respond?

I am curious what happens when Google Chrome encounters two variables with the same name. In my particular case, this issue arises in the code snippet available at this link, which is a small portion of the entire code. I am facing an issue where placing C ...

Best practices for establishing a conditional statement with JQuery's inArray function

I am working on a code snippet to generate a list of unique random numbers. Each generated number is supposed to be added to an array after checking that it doesn't already exist in the array. However, I seem to be facing some challenges with getting ...

Deleting lines from JSON object using Angular or JavaScript

On my webpage, I have a list where you can add a new line by pressing the "+" button (easy with push), but I'm not sure how to remove lines using the "X" button. https://i.stack.imgur.com/nm06A.png This is the JSON structure: "priceExtra" : [ ...

How to use ngModel directive in Angular to select/unselect dynamically generated checkboxes and retrieve their values

Currently, I am working with a dataset retrieved from an API and dynamically creating checkboxes in my HTML page using the DataView component from PrimeNG. My objective is to implement a feature where users can select or deselect all checkboxes with a cli ...

The anchorEl state in Material UI Popper is having trouble updating

I am currently facing an issue with the Material UI popper as the anchorEl state remains stuck at null. Although Material UI provides an example using a functional component, I am working with a class-based component where the logic is quite similar. I w ...