source

개체 또는 클래스 이름 가져오기

manysource 2022. 11. 14. 21:48

개체 또는 클래스 이름 가져오기

객체의 함수 이름을 얻을 수 있는 솔루션이 있습니까?

function alertClassOrObject (o) {
   window.alert(o.objectName); //"myObj" OR "myClass" as a String
}

function myClass () {
   this.foo = function () {
       alertClassOrObject(this);
   }
}

var myObj = new myClass();
myObj.foo();

for (var k in this) {...}- 에 대한 정보는 없습니다.className또는ObjectName하나 구할 수 있을까요?

객체의 생성자 함수를 가져온 다음 객체의 이름 속성을 검사합니다.

myObj.constructor.name

myClass를 반환합니다.

예:

function Foo () { console.log('Foo function'); }
var f = new Foo();
console.log('f', f.constructor.name); // -> "Foo"

var Bar = function () { console.log('Anonymous function (as Bar)'); };
var b = new Bar();
console.log('b', b.constructor.name); // -> "Bar"

var Abc = function Xyz() { console.log('Xyz function (as Abc)'); };
var a = new Abc();
console.log('a', a.constructor.name); // -> "Xyz"

class Clazz { constructor() { console.log('Clazz class'); } }
var c = new Clazz();
console.log('c', c.constructor.name); // -> "Clazz"

var otherClass = class Cla2 { constructor() { console.log('Cla2 class (as otherClass)'); } }
var c2 = new otherClass();
console.log('c2', c2.constructor.name); // -> "Cla2"

이미 답변이 있었으므로, JavaScript에서 객체의 생성자를 취득하는 방법의 차이점을 지적하고 싶습니다.생성자와 실제 개체/클래스 이름 사이에는 차이가 있습니다.다음 사항에 따라 의사결정이 복잡해진다면 다음과 같은 방법을 찾고 있을 수 있습니다.instanceof아니면 스스로에게 물어봐야 할지도 몰라. "내가 왜 이러는거지?"이게 정말 제가 해결하려는 건가요?"

주의:

obj.constructor.name는 이전 브라우저에서는 사용할 수 없습니다.매칭(\w+)ES6 스타일 클래스를 만족시켜야 합니다.

코드:

var what = function(obj) {
  return obj.toString().match(/ (\w+)/)[1];
};

var p;

// Normal obj with constructor.
function Entity() {}
p = new Entity();
console.log("constructor:", what(p.constructor), "name:", p.constructor.name , "class:", what(p));

// Obj with prototype overriden.
function Player() { console.warn('Player constructor called.'); }
Player.prototype = new Entity();
p = new Player();
console.log("constructor:", what(p.constructor), "name:", p.constructor.name, "class:", what(p));

// Obj with constructor property overriden.
function OtherPlayer() { console.warn('OtherPlayer constructor called.'); }
OtherPlayer.constructor = new Player();
p = new OtherPlayer();
console.log("constructor:", what(p.constructor), "name:", p.constructor.name, "class:", what(p));

// Anonymous function obj.
p = new Function("");
console.log("constructor:", what(p.constructor), "name:", p.constructor.name, "class:", what(p));

// No constructor here.
p = {};
console.log("constructor:", what(p.constructor), "name:", p.constructor.name, "class:", what(p));

// ES6 class.
class NPC { 
  constructor() {
  }
}
p = new NPC();
console.log("constructor:", what(p.constructor), "name:", p.constructor.name , "class:", what(p));

// ES6 class extended
class Boss extends NPC {
  constructor() {
    super();
  }
}
p = new Boss();
console.log("constructor:", what(p.constructor), "name:", p.constructor.name , "class:", what(p));

결과:

여기에 이미지 설명 입력

코드: https://jsbin.com/wikiji/edit?js,console

표준 IIE를 사용하는 경우(예: TypeScript)

var Zamboch;
(function (_Zamboch) {
    (function (Web) {
        (function (Common) {
            var App = (function () {
                function App() {
                }
                App.prototype.hello = function () {
                    console.log('Hello App');
                };
                return App;
            })();
            Common.App = App;
        })(Web.Common || (Web.Common = {}));
        var Common = Web.Common;
    })(_Zamboch.Web || (_Zamboch.Web = {}));
    var Web = _Zamboch.Web;
})(Zamboch || (Zamboch = {}));

시제품에 주석을 달 수 있습니다.

setupReflection(Zamboch, 'Zamboch', 'Zamboch');

다음으로 _fullname 필드와 _classname 필드를 사용합니다.

var app=new Zamboch.Web.Common.App();
console.log(app._fullname);

주석 기능은 다음과 같습니다.

function setupReflection(ns, fullname, name) {
    // I have only classes and namespaces starting with capital letter
    if (name[0] >= 'A' && name[0] <= 'Z') {
        var type = typeof ns;
        if (type == 'object') {
            ns._refmark = ns._refmark || 0;
            ns._fullname = fullname;
            var keys = Object.keys(ns);
            if (keys.length != ns._refmark) {
                // set marker to avoid recusion, just in case 
                ns._refmark = keys.length;
                for (var nested in ns) {
                    var nestedvalue = ns[nested];
                    setupReflection(nestedvalue, fullname + '.' + nested, nested);
                }
            }
        } else if (type == 'function' && ns.prototype) {
            ns._fullname = fullname;
            ns._classname = name;
            ns.prototype._fullname = fullname;
            ns.prototype._classname = name;
        }
    }
}

JsFiddle

이것을 시험해 보세요.

var classname = ("" + obj.constructor).split("function ")[1].split("(")[0];

저도 같은 문제에 직면해 있었습니다.여기서 제시한 해결책 중 제가 하고 있는 일에 최적인 것은 없었습니다.제가 가지고 있던 것은 콘텐츠를 모달로 표시하는 일련의 기능들이었고, 그것을 하나의 오브젝트 정의로 재팩터링하여 클래스의 함수, 메서드를 만들고 있었습니다.이 문제는 모달 자체 내에 몇 개의 네비게이션 버튼이 생성되어 있는 메서드 중 하나가 함수 중 하나(현재 클래스의 객체)에 onClick을 사용한다는 것을 발견했을 때 발생했습니다.이러한 네비게이션버튼을 처리하기 위한 다른 방법을 검토 중(또 검토 중)이지만 부모창에서 정의된 변수를 스위프하여 클래스 자체의 변수 이름을 찾을 수 있었습니다.클래스 인스턴스(instance of)와 일치하는 항목을 검색하여 여러 개의 인스턴스가 있을 수 있는 경우 각 인스턴스에서 고유할 수 있는 특정 속성을 비교했습니다.

var myClass = function(varName)
{
    this.instanceName = ((varName != null) && (typeof(varName) == 'string') && (varName != '')) ? varName : null;

    /**
     * caching autosweep of window to try to find this instance's variable name
     **/
    this.getInstanceName = function() {
        if(this.instanceName == null)
        {
            for(z in window) {
                if((window[z] instanceof myClass) && (window[z].uniqueProperty === this.uniqueProperty)) {
                    this.instanceName = z;
                    break;
                }
            }
        }
        return this.instanceName;
    }
}

필요한 것은 다음과 같습니다.

  1. 함수의 상수를 줄 바꿈(함수의 이름은 가져올 객체의 이름과 동일)
  2. 개체 내에서 화살표 기능 사용

console.clear();
function App(){ // name of my constant is App
  return {
  a: {
    b: {
      c: ()=>{ // very important here, use arrow function 
        console.log(this.constructor.name)
      }
    }
  }
}
}
const obj = new App(); // usage

obj.a.b.c(); // App

// usage with react props etc, 
// For instance, we want to pass this callback to some component

const myComponent = {};
myComponent.customProps = obj.a.b.c;
myComponent.customProps(); // App

런타임 중에 클래스 이름을 가져오는 가장 효율적인 방법

let className = this.constructor.name

언급URL : https://stackoverflow.com/questions/10314338/get-name-of-object-or-class