What are the steps to create a function that behaves like instanceof when given a string as input

Is there a way to achieve something similar to this?

var isChild = isInstanceOf( var1, 'Constructor')

so that it is equivalent to

var isChild = (var1 instanceof Constructor)

The challenge is that the function Constructor is not available in the current scope, so I am looking to pass a string instead.

I believe one approach could be to traverse up the prototype chain to obtain the constructor.toString() and then compare it, but I am unsure of how to accomplish this.

--

Allow me to provide more context as I have come across a better solution

I encountered a circular reference between two function constructors, and when attempting to reference it, RequireJS continuously returned undefined. (In this scenario, Constructor would be undefined.)

I came across this helpful information: http://requirejs.org/docs/api.html#circular

Here is the snippet of code that caused the issue:

//(in BaseControl.js)

define(['src/utils/models/Field'], 
  function(Field) {
[...]

  setField: function(field) {

    if (!field instanceof Field) throw new Error('field should be an instance of Field');
    [...]

The issue stemmed from the fact that Field also required BaseControl, resulting in Field being undefined, leading to the following error:

Uncaught TypeError: Expecting a function in instanceof check, but got false 

I managed to resolve this by following the requireJS documentation:

define(['require', 'src/utils/models/Field'], 
  function(require, Field,) {
[...]

  setField: function(field) {

    if (!Field) Field = require('src/utils/models/Field');

    if (!field instanceof Field) throw new Error('field should be an instance of Field');
    [...]

Answer №1

If you're looking for a way to determine if an object is an instance of a specific constructor, you can use the following function:

function isInstanceOf(obj, constrname) {
    do {
        if (Object.prototype.hasOwnProperty.call(obj, "constructor")
          && typeof obj.constructor === "function"
          && obj.constructor.name == constrname )
            return true;
    } while (obj = Object.getPrototypeOf(obj))
    return false;
}

Keep in mind, however, that this method may not work reliably as the name property is non-standard and not supported by IE. Additionally, it may not work with anonymous functions. If you need a more robust solution, consider looking into Duck typing. You can find more information on this topic at . For a comprehensive guide on implementing interfaces in JavaScript, check out the book Pro JavaScript Design Patterns, specifically Chapter 2 on Interfaces (Google Books).

Answer №2

After considering your suggestions, I have crafted the following concise code snippet along with a relevant example:

    <SCRIPT LANGUAGE="javascript" TYPE="text/javascript">
function _check_data_type( _obj, _datatype )
{
    if ( _obj == null || _obj == "undefined" ) return -1 ;
    var _constructor = _obj.constructor + "" ;
    return ( typeof _obj === _datatype.toLowerCase() ||
             ( _constructor.toLowerCase().indexOf( _datatype.toLowerCase() ) != -1 ) ) ? 1 : 0 ;
}

    var _str1 = new String( "woow" );
    var _str2 = "woow" ;
    var _pi = 3.14 ;

    function myobj()
    {
        this.contents = "The apple is on the table" ;
    }

    var _array = new Array( 1, 2, 3, 4 ) ; 
    var _myobj = new myobj();

    document.write( "Casting the string 'woow' via object assignment: " + " >> " + ( _check_data_type( _str1, "string" ) ? "It's string" : "Not a string" ) + "<br>" ) ;
    document.write( "Casting the string 'woow' via literal assignment: " + " >> " + ( _check_data_type( _str2, "string" ) ? "It's string" : "Not a string" ) + "<br>" ) ;
    document.write( "Is PI a number? " + " >> " + ( _check_data_type( _pi, "number" ) ? "Yes, it is" : "No !" ) + "<br>" ) ;
    document.write( "Is this an object of mine ? " + " >> " + ( _check_data_type( _myobj, "myobj" ) ? "Yes, it's yours, see contents : '" + _myobj.contents + "'" : "No !" ) + "<br>" ) ;
    document.write( "Is this an array obj? " + " >> " + ( _check_data_type( _array, "array" ) ? "Yes, it's an array" : "No !" ) + "<br>" ) ;
    </SCRIPT>

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

"Unlocking the power of AngularJS translate: A step-by-step

I'm seeking answers to two questions. 1) How can I utilize angularjs translate with ng-repeat? Although my Json file works fine, the text does not display when using ng-repeat. Here is a snippet from my json: "rules":{ "points":[ {"t ...

When React object state remains unchanged, the page does not update automatically

i have a state object with checkboxes: const [checkboxarray_final, setCheckboxarray_final] = useState({ 2: ",4,,5,", 9: ",1,", }); i'm working on enabling check/uncheck functionality for multiple checkboxes: these are ...

The VueJS Chosen directive fails to refresh when new options are selected

Struggling to populate my jQuery Chosen dropdown field with AJAX data using VueJS. Unfortunately, when trying to update the values, the Chosen dropdown does not reflect the changes. I've experimented with different approaches, including manually trig ...

There was an error while trying to read the properties of undefined (specifically the state). Make sure to include this.state.a

I am struggling with an error that I have never encountered before. Despite having experience working with functional components, I am new to class components. I used create react app to install the application, but it seems like I might be missing a req ...

Unable to prolong TypeScript document

As I develop a drag and drop interface, upon dropping a file, the native File is retrieved. To enhance this interface with additional information, I decided to explore various approaches. In my initial attempt, I utilized: interface AcceptedFile extends ...

Developing microfrontends using Angular involves loading and navigating a compiled package from npm

I have been struggling to find a solution to an ongoing issue and wasting time on futile attempts. Currently, I am working with Angular 15 within a microfrontend architecture. My goal is to implement a system where I can download a compiled microfrontend ...

What could be causing the hover effect to not work on other elements within the div?

I am working on creating a card that displays only the image when not hovered, but expands and reveals additional information in a div to the right of the image when hovered. Unfortunately, when I hover over the image and then move towards the adjacent div ...

Error message: When accessing react-native camera roll, the message "this.state.photos is not a valid object" appears

Encountering an error while attempting to implement camera roll functionality in my demo app. The error states, "null is not an object (evaluating 'this.state.photos')" View iOS Error Message. I am a beginner developer working on my first react-n ...

Having trouble with the jQuery function not working as expected? Can't seem to identify any errors in the code?

I'm attempting to capture the essence of moving clouds from this beautiful theme: (I purchased it on themeforest, but it's originally designed for tumblr) Now, I want to incorporate it into my wordpress website here: The code used to be under ...

Leveraging nested objects within React state

A React child cannot be an object. If you intended to render a collection of children, utilize an array Encountering the error mentioned above has left me puzzled regarding its restrictions. Below is the code where I am facing this issue. It includes an o ...

Here is a helpful guide on updating dropdown values in real time by retrieving data from an SQL database

This feature allows users to select a package category from a dropdown menu. For example, selecting "Unifi" will display only Unifi packages, while selecting "Streamyx" will show only Streamyx packages. However, if I first select Unifi and then change to S ...

Execute an AJAX post request to the identical PHP page (utilizing the Jquery Form Plugin)

I am in the process of developing a new web interface using JavaTMP, an AJAX-based admin template. After spending time understanding its functionality, I have created a page with a form to allow users to create projects within my software. Typically, creat ...

The issue arises when trying to use destructured imports with Mongoose

I've been developing a straightforward Express app with ES6. In the process of creating a schema and model for Mongoose, I encountered an issue with the following syntax: import mongoose, { Schema } from 'mongoose'; const PostSchema = new ...

Real-time File Updates Display with Node.js and Express.js

Seeking guidance on whether there is a Node module available to utilize the Express module for displaying real-time updates in the browser using data from a file. I have a regularly updated .csv file and I am looking to showcase these updates instantly on ...

What are the steps to fix the "Invariant Violation" issue that is linked to the redux store?

During my DOM testing to verify if a dialog box would open upon clicking a button, I encountered an error message: Invariant Violation: Could not find "store" in either the context or props of >"Connect(Photos)". Either wrap the root component in a , ...

Retrieve the element that triggered the event listener within Nuxt

I am currently developing a Nuxt project where I have set up my component using the code below. The select-parent-container has a click event attached to it. Whenever this event is triggered, I need to identify and return the specific parent container that ...

Exploring the mechanics of JavaScript and jQuery Ajax: What's the secret to its function

It's common knowledge that browsers are single-threaded, meaning they can only either render the UI or execute Javascript snippets. While web workers offer a way to achieve multi-threading, let's focus on the default behavior. I'm curious a ...

Incorporating a parameter into a <div> only when the parameter holds a value

Being new to web development, I have a rather basic query. If the datainfo prop variable is not empty, I'd like to include a data attribute in the div tag. <div style={{height: props.height - handleHeight()}} data={datainfo ? datainfo : ""}> C ...

Sending the method's URL in the controller through an AJAX call

Below is the code snippet for an ajax call: <script> jQuery(document).ready(function() { $("#VEGAS").submit(function(){ var form_data = $("#VEGAS").serialize(); var routeUrl = "<?= url('/'); ?> /PUBLIC/vpage"; $.ajax({ ...

What is the best way to transfer variables between PHP and an external JavaScript file?

I need to transfer 2 variables (which store data for a chart) to an external JS file that contains the chart settings. In my PHP code, I have: <script type='text/javascript'> var final_values = '$final_values'; var final_names = ...