Constructor name lookup in JavaScript

I need to implement two functions in JavaScript: isConstructor(x)andconstructorName(x)

isConstructor(x)should return trueif the argument xis a constructor function and false, otherwise. For instance,

isConstructor(Date)      ===  true
isConstructor(Math.cos)  ===  false

constructorName(x)should return a constructor name for each corresponding constructor function x. For example,

constructorName(Date)  ===  'Date'

I can only think of an ugly implementation for both functions, where I create the string command"var y = new x ()" which is then called using the eval(command)in expression try/catch. If this call evalsucceeds at all, I call the xconstructor. And I get the name xindirectly by asking for the name of the prototype class y, something like

var constrName = Object.prototype.toString.call(y).slice(8,-1); // extracts the `ConstrName` from `[object ConstrName]`
return constrName;

, . ?

+4
5

JavaScript, (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function). , , , :

function isConstructor(x) {
    return typeof x === 'function' && typeof x.prototype !== 'undefined';
}

, Function.prototype.toString.apply(x) , , , jQuery, , .. .

+2

; new TypeError:

function isConstructor(fn)
{
    try {
        var r = new fn(); // attempt instantiation
    } catch (e) {
        if (e instanceof TypeError) {
            return false; // probably shouldn't be called as constructor
        }
        throw e; // something else went wrong
    }
    return true; // some constructors may not return an instance of itself
}

:

  • TypeError , , ;
  • ;
  • , instanceof obj === func;
  • .
+1

- , [[Construct]]. - , . , [[Class]], Object.prototype.toString.

ECMAScript , .

function foo(){}

. - , [[Call]], typeof "". ,

typeof document.getElementById  // function

new document.getElementById()

, . , :

typeof XMLHttpRequest  // object

XMLHttpRequest - , [[Call]], :

var x = XMLHttpRequest() // TypeError: XMLHttpRequest isn't a function

, prototype, , , prototype , native.

, , try..catch, , .

+1

, :

function isConstructor(func) {
    var t = new func();
    return (t instanceof func);
}

: , . . , ( ) , , , .

0

! , , , ECMAScript, . . !

0

Source: https://habr.com/ru/post/1543402/


All Articles