JavaScript 객체의 클래스를 얻는 방법? 어떻게 확인할 수 있습니까? Java의

JavaScript 객체를 만들었지 만 해당 객체의 클래스를 어떻게 확인할 수 있습니까?

Java의 .getClass()방법 과 비슷한 것을 원합니다 .



답변

getClass()JavaScript 에는 Java와 정확히 일치하는 것이 없습니다 . 자바는 클래스 기반 언어 가 아닌 프로토 타입 기반 언어 이기 때문 입니다.

필요한 것에 따라 getClass()JavaScript에는 몇 가지 옵션이 있습니다.

몇 가지 예 :

function Foo() {}
var foo = new Foo();

typeof Foo;             // == "function"
typeof foo;             // == "object"

foo instanceof Foo;     // == true
foo.constructor.name;   // == "Foo"
Foo.name                // == "Foo"    

Foo.prototype.isPrototypeOf(foo);   // == true

Foo.prototype.bar = function (x) {return x+x;};
foo.bar(21);            // == 42

참고 : Uglify로 코드를 컴파일하는 경우 비전 역 클래스 이름이 변경됩니다. 이를 방지하기 위해, 추하게는이 --mangle사용되어 false로 설정할 수 PARAM 꿀꺽 또는 불평 소리를 .


답변

obj.constructor.name

최신 브라우저에서 신뢰할 수있는 방법입니다. Function.nameES6 표준에 공식적으로 추가되어 JavaScript 객체의 “클래스”를 문자열로 가져 오는 표준 준수 수단이되었습니다. 객체가로 인스턴스화되면 var obj = new MyClass()“MyClass”가 반환됩니다.

숫자에 대해서는 “Number”, 배열에 대해서는 “Array”, 함수에 대해서는 “Function”등을 반환합니다. 일반적으로 예상대로 동작합니다. 프로토 타입이나 via없이 객체를 만들 Object.create( null )거나 익명으로 정의 된 (이름이없는) 함수에서 객체를 인스턴스화 한 경우에만 실패 합니다.

또한 코드를 축소하는 경우 하드 코딩 된 유형 문자열과 비교하는 것이 안전하지 않습니다. 예를 들어 확인하는 obj.constructor.name == "MyType"대신 확인하십시오 obj.constructor.name == MyType.name. 또는 생성자 자체를 비교하면 각 DOM에 생성자 함수의 다른 인스턴스가 있으므로 생성자에 대한 객체 비교를 수행 할 수 없으므로 DOM 경계를 넘어서 작동하지 않습니다.


답변

이 함수는 "Undefined"정의되지 않은 값과 "Null"null을 반환 합니다 .
다른 모든 값의 경우 CLASSNAME-part가에서 추출되어 [object CLASSNAME]사용 Object.prototype.toString.call(value)됩니다.

function getClass(obj) {
  if (typeof obj === "undefined") return "Undefined";
  if (obj === null) return "Null";
  return Object.prototype.toString.call(obj).match(/^\[object\s(.*)\]$/)[1];
}

getClass("")   === "String";
getClass(true) === "Boolean";
getClass(0)    === "Number";
getClass([])   === "Array";
getClass({})   === "Object";
getClass(null) === "Null";
// etc...


답변

“의사 클래스”를 얻으려면 다음과 같이 생성자 함수를 얻을 수 있습니다.

obj.constructor

constructor상속을 할 때가 올바르게 설정 되었다고 가정하면 다음과 같습니다.

Dog.prototype = new Animal();
Dog.prototype.constructor = Dog;

이 두 줄은

var woofie = new Dog()

woofie.constructor가리킬 것 Dog입니다. 참고 Dog생성자 함수이며,이다 Function객체입니다. 그러나 당신은 할 수 있습니다 if (woofie.constructor === Dog) { ... }.

클래스 이름을 문자열로 얻으려면 다음이 잘 작동합니다.

http://blog.magnetiq.com/post/514962277/finding-out-class-names-of-javascript-objects

function getObjectClass(obj) {
    if (obj && obj.constructor && obj.constructor.toString) {
        var arr = obj.constructor.toString().match(
            /function\s*(\w+)/);

        if (arr && arr.length == 2) {
            return arr[1];
        }
    }

    return undefined;
}

생성자 함수를 가져 와서 문자열로 변환하고 생성자 함수의 이름을 추출합니다.

참고는 obj.constructor.name잘 작동 수도 있지만, 표준이 아니다. Chrome 및 Firefox에는 있지만 IE 9 또는 IE 10 RTM을 포함한 IE에는 없습니다.


답변

constructor 속성 을 사용하여 객체를 만든 생성자 함수에 대한 참조를 얻을 수 있습니다 .

function MyObject(){
}

var obj = new MyObject();
obj.constructor; // MyObject

런타임에 객체 유형을 확인해야하는 경우 instanceof 연산자를 사용할 수 있습니다 .

obj instanceof MyObject // true


답변

이전 버전과의 호환성 인 ECMAScript 6에 대한 끊임없는 기록을 유지하면서 JavaScript는 여전히 class유형을 갖지 않습니다 (모두가 이것을 이해하는 것은 아님). 그것은 않습니다class자사의 일환으로 키워드 class프로토 타입 -하지만 작성하기위한 구문 여전히 클래스라는 어떤 일을 . JavaScript는 지금은 아니고 고전적인 OOP 언어 가 아닙니다 . 클래스 측면에서 JS에 대해 말하는 것은 오해의 소지가 있거나 아직 프로토 타입 상속을하지 않은 징후 일뿐입니다 (실제로 유지).

이는 this.constructor여전히 constructor함수에 대한 참조를 얻는 좋은 방법 입니다. 그리고 this.constructor.prototype프로토 타입 자체에 액세스하는 방법입니다. 이것은 자바가 아니기 때문에 클래스가 아닙니다. 인스턴스가 인스턴스화 된 프로토 타입 객체입니다. 다음은 프로토 타입 체인을 만들기 위해 ES6 구문 설탕을 사용하는 예입니다.

class Foo {
  get foo () {
    console.info(this.constructor, this.constructor.name)
    return 'foo'
  }
}

class Bar extends Foo {
  get foo () {
    console.info('[THIS]', this.constructor, this.constructor.name, Object.getOwnPropertyNames(this.constructor.prototype))
    console.info('[SUPER]', super.constructor, super.constructor.name, Object.getOwnPropertyNames(super.constructor.prototype))

    return `${super.foo} + bar`
  }
}

const bar = new Bar()
console.dir(bar.foo)

이것이 다음을 사용하여 출력되는 것입니다 babel-node.

> $ babel-node ./foo.js                                                                                                                    6.2.0 master ●]
[THIS] [Function: Bar] 'Bar' [ 'constructor', 'foo' ]
[SUPER] [Function: Foo] 'Foo' [ 'constructor', 'foo' ]
[Function: Bar] 'Bar'
'foo + bar'

거기 있어요! 2016 년에는 classJavaScript에 키워드가 있지만 클래스 유형은 없습니다. this.constructor생성자 함수 this.constructor.prototype를 얻는 가장 좋은 방법이며 프로토 타입 자체에 액세스하는 가장 좋은 방법입니다.


답변

나는 지금 일반적인 일을하고 이것을 사용했다 :

class Test {
  // your class definition
}

nameByType = function(type){
  return type.prototype["constructor"]["name"];
};

console.log(nameByType(Test));

그것이 객체의 인스턴스가없는 경우 유형 입력으로 클래스 이름을 얻는 유일한 방법입니다.

(ES2017로 작성)

도트 표기법도 잘 작동합니다

console.log(Test.prototype.constructor.name); // returns "Test"