简体   繁体   中英

JavaScript + Get object / function name

I am building an app with JavaScript. This app integrates with a third-party library. That library defines an object like this:

getLibrary().SomeObject = function() {
  function SomeObject(attrs) {
    this.id = attrs.id;
    this.description = attrs.description || '';

    this.result = {
      id: this.id,
      description: this.description,
    };
  }

  SomeObject.prototype.doSomething = function(actual) {
    return 'do something';
  };

  SomeObject.prototype.calculate = function() {
    return 42;
  };

  return SomeObject;
};

I have an instance of this object in a variable called myInstance . When I do a console.log(myInstance) , I see the following in the Chrome console window:

v SomeObject
  id: '1'
  description: 'my description'
  > result: Object

I am trying to get the "SomeObject" part from above. I tried:

if (myInstance instanceof SomeObject) {
  ...
}

However, that didn't work. I'm basically trying to get the name of the "type" (or function?). How do I get that from myInstance ?

Thanks

getLibrary().SomeObject is not a constructor function, it's a function that returns a constructor function. So to use it, you'd do something like:

var SomeObject = getLibrary().SomeObject();
// Note --------------------------------^^

...to call it to get back the constructor function it returns.

Then if you use that to create an instance:

var myInstance = new SomeObject({id:"some_id"});

... instanceof will work correctly:

console.log(myInstance instanceof SomeObject); // true

Live Example:

 var library = {}; function getLibrary() { return library; } getLibrary().SomeObject = function() { function SomeObject(attrs) { this.id = attrs.id; this.description = attrs.description || ''; this.result = { id: this.id, description: this.description, }; } SomeObject.prototype.doSomething = function(actual) { return 'do something'; }; SomeObject.prototype.calculate = function() { return 42; }; return SomeObject; }; var SomeObject = getLibrary().SomeObject(); var myInstance = new SomeObject({id: "myid"}); document.body.innerHTML = myInstance instanceof SomeObject; 

If you want to know what function (probably) created myInstance , provided nothing has messed up SomeObject.prototype (as they routinely do), you can get it from myInstance.constructor . As of ES2015, you can get the name of that function from its name property, and several browsers have supported that for years even though it's only recently been standardized. So (on compliant browsers):

console.log(myInstance.constructor.name); // "SomeObject"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM