etc./StackOverFlow

개체 유형의 이름을 가져옵니다.

청렴결백한 만능 재주꾼 2023. 4. 28. 04:05
반응형

질문자 :Ewen Cartwright


Javaclass.getName() 해당하는 JavaScript 가 있습니까?



class.getName() 해당하는 JavaScript가 있습니까?

아니 .

ES2015 업데이트 : class Foo {} 의 이름은 Foo.name 입니다. thing 의 유형에 관계없이 thing 의 클래스 이름 thing.constructor.name 입니다. ES2015 환경의 내장 생성자는 올바른 name 속성을 가지고 있습니다. 예를 들어 (2).constructor.name"Number" 입니다.


그러나 다음은 모두 어떤 식으로든 실패하는 다양한 해킹입니다.

여기에 필요한 작업을 수행할 수 있는 해킹이 있습니다. 이는 개체의 프로토타입을 수정한다는 점에 유의하세요.

 Object.prototype.getName = function() { var funcNameRegex = /function (.{1,})\(/; var results = (funcNameRegex).exec((this).constructor.toString()); return (results && results.length > 1) ? results[1] : ""; };

이제 모든 객체에는 생성자의 이름을 문자열로 반환하는 getName() FF3IE7 에서 이것을 테스트했는데 다른 구현에 대해서는 말할 수 없습니다.

그렇게 하고 싶지 않다면 여기에 JavaScript에서 유형을 결정하는 다양한 방법에 대한 설명이 있습니다...


나는 최근에 이것을 조금 더 철저하게 업데이트했지만 거의 그렇지 않습니다. 수정 환영...

constructor 속성을 사용하여...

모든 object constructor 속성에 대한 값이 object 가 생성된 방법과 해당 값으로 수행하려는 작업에 따라 유용하거나 유용하지 않을 수 있습니다.

일반적으로 다음과 같이 constructor 속성을 사용하여 객체의 유형을 테스트할 수 있습니다.

 var myArray = [1,2,3]; (myArray.constructor == Array); // true

따라서 대부분의 요구 사항에 충분히 적합합니다. 그 말은...

주의 사항

많은 경우에 전혀 작동하지 않습니다

이 패턴은 깨졌지만 매우 일반적입니다.

 function Thingy() { } Thingy.prototype = { method1: function() { }, method2: function() { } };

Objects 를 통해 구성된 new Thingy 해야합니다 constructor 속성을 가리키는 그 Object ,하지 Thingy . 그래서 우리는 처음부터 넘어집니다. 제어하지 않는 코드베이스의 constructor 를 신뢰할 수 없습니다.

다중 상속

명확하지 않은 예는 다중 상속을 사용하는 것입니다.

 function a() { this.foo = 1;} function b() { this.bar = 2; } b.prototype = new a(); // b inherits from a

이제 예상대로 작동하지 않습니다.

 var f = new b(); // instantiate a new object with the b constructor (f.constructor == b); // false (f.constructor == a); // true

한다면, 당신은 예기치 않은 결과를 얻을 수 있습니다 object 당신의 테스트가 다른이 object 의 같은 세트 prototype . 이 논의의 범위를 벗어나는 방법이 있습니다.

constructor 속성에 대한 다른 용도가 있습니다. 그 중 일부는 흥미롭고 나머지는 그다지 많지 않습니다. 지금은 이 논의와 관련이 없기 때문에 이러한 용도에 대해서는 자세히 다루지 않을 것입니다.

교차 프레임 및 교차 창에서 작동하지 않음

iframe 또는 팝업 창과 같이 window 개체에서 오는 개체 유형을 확인하려는 경우 유형 검사에 .constructor 를 사용하면 중단됩니다. 이는 각 `창' constructor 의 다른 버전이 있기 때문입니다. 즉,

 iframe.contentWindow.Array === Array // false

instanceof 연산자를 사용하여...

instanceof object 유형을 테스트하는 깔끔한 방법이기도 constructor 속성과 마찬가지로 자체 잠재적인 문제가 있습니다.

 var myArray = [1,2,3]; (myArray instanceof Array); // true (myArray instanceof Object); // true

그러나 instanceof 는 리터럴 값에 대해 작동하지 않습니다(리터럴은 Objects 가 아니기 때문에).

 3 instanceof Number // false 'abc' instanceof String // false true instanceof Boolean // false

예를 들어 instanceof 가 작동하려면 Object 로 감싸야 합니다.

 new Number(3) instanceof Number // true

.constructor 검사는 리터럴에 대해 잘 작동합니다 . 메서드 호출은 암시적으로 리터럴을 해당 개체 유형으로 래핑합니다.

 3..constructor === Number // true 'abc'.constructor === String // true true.constructor === Boolean // true

왜 3에 두 개의 점이 있습니까? Javascript는 첫 번째 점을 소수점으로 해석하기 때문에 ;)

교차 프레임 및 교차 창에서 작동하지 않음

instanceof constructor 속성 검사와 같은 이유로 다른 창에서 작동하지 않습니다.


constructor 속성 name 속성을 사용하여...

많은 경우에 전혀 작동하지 않습니다

다시, 위를 참조하십시오. constructor 가 완전히 그리고 완전히 잘못되고 쓸모가 없는 것은 매우 일반적입니다.

<IE9에서 작동하지 않음

myObjectInstance.constructor.name 을 사용하면 사용 constructor 함수의 이름이 포함된 문자열을 얻을 수 있지만 앞서 언급한 constructor 속성에 대한 주의 사항이 적용됩니다.

IE9 이상에서는 다음 을 지원하는 원숭이 패치를 할 수 있습니다.

 if (Function.prototype.name === undefined && Object.defineProperty !== undefined) { Object.defineProperty(Function.prototype, 'name', { get: function() { var funcNameRegex = /function\s+([^\s(]+)\s*\(/; var results = (funcNameRegex).exec((this).toString()); return (results && results.length > 1) ? results[1] : ""; }, set: function(value) {} }); }

문제의 기사에서 업데이트된 버전입니다. 이것은 기사가 게시된 지 3개월 후에 추가되었으며 기사 작성자 Matthew Scharley가 사용하도록 권장하는 버전입니다. 이 변경은 이전 코드의 잠재적인 함정 을 지적하는 주석에서 영감을 받았습니다.

 if (Function.prototype.name === undefined && Object.defineProperty !== undefined) { Object.defineProperty(Function.prototype, 'name', { get: function() { var funcNameRegex = /function\s([^(]{1,})\(/; var results = (funcNameRegex).exec((this).toString()); return (results && results.length > 1) ? results[1].trim() : ""; }, set: function(value) {} }); }

Object.prototype.toString 사용

이 게시물이 자세히 설명 하듯 Object.prototype.toString toString 저수준 및 일반 구현)을 사용하여 모든 내장 유형에 대한 유형을 가져올 수 있습니다.

 Object.prototype.toString.call('abc') // [object String] Object.prototype.toString.call(/abc/) // [object RegExp] Object.prototype.toString.call([1,2,3]) // [object Array]

다음과 같은 짧은 도우미 함수를 작성할 수 있습니다.

 function type(obj){ return Object.prototype.toString.call(obj).slice(8, -1); }

cruft를 제거하고 유형 이름만 얻으려면

 type('abc') // String

그러나 모든 사용자 정의 유형에 대해 Object


모두를 위한 주의사항...

이들 모두는 하나의 잠재적인 문제의 대상이 되며, 문제의 대상이 어떻게 구성되었는지에 대한 질문입니다. 다음은 객체를 빌드하는 다양한 방법과 다양한 유형 검사 방법이 반환하는 값입니다.

 // using a named function: function Foo() { this.a = 1; } var obj = new Foo(); (obj instanceof Object); // true (obj instanceof Foo); // true (obj.constructor == Foo); // true (obj.constructor.name == "Foo"); // true // let's add some prototypical inheritance function Bar() { this.b = 2; } Foo.prototype = new Bar(); obj = new Foo(); (obj instanceof Object); // true (obj instanceof Foo); // true (obj.constructor == Foo); // false (obj.constructor.name == "Foo"); // false // using an anonymous function: obj = new (function() { this.a = 1; })(); (obj instanceof Object); // true (obj.constructor == obj.constructor); // true (obj.constructor.name == ""); // true // using an anonymous function assigned to a variable var Foo = function() { this.a = 1; }; obj = new Foo(); (obj instanceof Object); // true (obj instanceof Foo); // true (obj.constructor == Foo); // true (obj.constructor.name == ""); // true // using object literal syntax obj = { foo : 1 }; (obj instanceof Object); // true (obj.constructor == Object); // true (obj.constructor.name == "Object"); // true

이 예제 세트에 모든 순열이 있는 것은 아니지만 필요에 따라 상황이 얼마나 지저분해질 수 있는지에 대한 아이디어를 제공하기에 충분하기를 바랍니다. 아무것도 가정하지 마십시오. 정확히 무엇을 추구하는지 이해하지 못하면 미묘함을 이해하지 못하기 때문에 예상하지 못한 부분에서 코드가 깨질 수 있습니다.

노트:

typeof 연산자에 대한 논의는 object 가 매우 단순하기 때문에 주어진 유형인지 여부를 식별하는 데 실제로 유용하지 않습니다. typeof 가 유용한 위치를 이해하는 것이 중요하지만 현재로서는 이것이 이 토론과 크게 관련이 있다고 생각하지 않습니다. 내 마음은 변화에 열려 있습니다. :)


Community Wiki

Jason Bunting의 답변은 내가 필요한 것을 찾는 데 충분한 단서를 제공했습니다.

 <<Object instance>>.constructor.name

예를 들어 다음 코드에서:

 function MyObject() {} var myInstance = new MyObject();

myInstance.constructor.name"MyObject" 반환합니다.


Ewen Cartwright

내가 사용하는 약간의 트릭 :

 function Square(){ this.className = "Square"; this.corners = 4; } var MySquare = new Square(); console.log(MySquare.className); // "Square"

Daniel Szabo

업데이트

정확히 말하면 OP가 특정 개체의 생성자 이름을 검색하는 함수를 요청했다고 생각합니다. 자바스크립트에서 object 는 타입이 없지만 and 그 자체 로 타입이다. 그러나 다른 객체는 다른 생성자를 가질 수 있습니다.

 Object.prototype.getConstructorName = function () { var str = (this.prototype ? this.prototype.constructor : this.constructor).toString(); var cname = str.match(/function\s(\w*)/)[1]; var aliases = ["", "anonymous", "Anonymous"]; return aliases.indexOf(cname) > -1 ? "Function" : cname; } new Array().getConstructorName(); // returns "Array" (function () {})().getConstructorName(); // returns "Function"


참고: 아래 예제는 더 이상 사용되지 않습니다.

Christian Sciberras 가 링크한 블로그 게시물 에는 이를 수행하는 방법에 대한 좋은 예가 포함되어 있습니다. 즉, Object 프로토타입을 확장하여:

 if (!Object.prototype.getClassName) { Object.prototype.getClassName = function () { return Object.prototype.toString.call(this).match(/^\[object\s(.*)\]$/)[1]; } } var test = [1,2,3,4,5]; alert(test.getClassName()); // returns Array

Saul

Object.prototype.toString 사용

이 게시물에서 자세히 설명했듯이 toString의 저수준 및 일반 구현인 Object.prototype.toString을 사용하여 모든 내장 유형에 대한 유형을 가져올 수 있습니다.

 Object.prototype.toString.call('abc') // [object String] Object.prototype.toString.call(/abc/) // [object RegExp] Object.prototype.toString.call([1,2,3]) // [object Array]

다음과 같은 짧은 도우미 함수를 작성할 수 있습니다.

 function type(obj){ return Object.prototype.toString.call(obj]).match(/\s\w+/)[0].trim() } return [object String] as String return [object Number] as Number return [object Object] as Object return [object Undefined] as Undefined return [object Function] as Function

Gaurav Ramanan

다음은 instanceof의 단점을 해결하는 솔루션입니다. 크로스 윈도우 및 크로스 프레임에서 객체의 유형을 확인할 수 있으며 기본 유형에 문제가 없습니다.

 function getType(o) { return Object.prototype.toString.call(o).match(/^\[object\s(.*)\]$/)[1]; } function isInstance(obj, type) { var ret = false, isTypeAString = getType(type) == "String", functionConstructor, i, l, typeArray, context; if (!isTypeAString && getType(type) != "Function") { throw new TypeError("type argument must be a string or function"); } if (obj !== undefined && obj !== null && obj.constructor) { //get the Function constructor functionConstructor = obj.constructor; while (functionConstructor != functionConstructor.constructor) { functionConstructor = functionConstructor.constructor; } //get the object's window context = functionConstructor == Function ? self : functionConstructor("return window")(); //get the constructor for the type if (isTypeAString) { //type is a string so we'll build the context (window.Array or window.some.Type) for (typeArray = type.split("."), i = 0, l = typeArray.length; i < l && context; i++) { context = context[typeArray[i]]; } } else { //type is a function so execute the function passing in the object's window //the return should be a constructor context = type(context); } //check if the object is an instance of the constructor if (context) { ret = obj instanceof context; if (!ret && (type == "Number" || type == "String" || type == "Boolean")) { ret = obj.constructor == context } } } return ret; }

isInstance에는 객체와 유형이라는 두 개의 매개변수가 필요합니다. 작동 방식에 대한 실제 트릭은 개체가 동일한 창에서 왔는지 확인하고 그렇지 않은 경우 개체의 창을 가져오는지 확인하는 것입니다.

예:

 isInstance([], "Array"); //true isInstance("some string", "String"); //true isInstance(new Object(), "Object"); //true function Animal() {} function Dog() {} Dog.prototype = new Animal(); isInstance(new Dog(), "Dog"); //true isInstance(new Dog(), "Animal"); //true isInstance(new Dog(), "Object"); //true isInstance(new Animal(), "Dog"); //false

유형 인수는 생성자를 반환하는 콜백 함수일 수도 있습니다. 콜백 함수는 제공된 객체의 창인 하나의 매개변수를 받습니다.

예:

 //"Arguments" type check var args = (function() { return arguments; }()); isInstance(args, function(w) { return w.Function("return arguments.constructor")(); }); //true //"NodeList" type check var nl = document.getElementsByTagName("*"); isInstance(nl, function(w) { return w.document.getElementsByTagName("bs").constructor; }); //true

명심해야 할 한 가지는 IE < 9는 모든 객체에 대한 생성자를 제공하지 않으므로 NodeList에 대한 위의 테스트는 false를 반환하고 isInstance(alert, "Function")도 false를 반환한다는 것입니다.


Eli

나는 실제로 비슷한 것을 찾고 있었고이 질문을 발견했습니다. 유형을 얻는 방법은 다음과 같습니다. jsfiddle

 var TypeOf = function ( thing ) { var typeOfThing = typeof thing; if ( 'object' === typeOfThing ) { typeOfThing = Object.prototype.toString.call( thing ); if ( '[object Object]' === typeOfThing ) { if ( thing.constructor.name ) { return thing.constructor.name; } else if ( '[' === thing.constructor.toString().charAt(0) ) { typeOfThing = typeOfThing.substring( 8,typeOfThing.length - 1 ); } else { typeOfThing = thing.constructor.toString().match( /function\s*(\w+)/ ); if ( typeOfThing ) { return typeOfThing[1]; } else { return 'Function'; } } } else { typeOfThing = typeOfThing.substring( 8,typeOfThing.length - 1 ); } } return typeOfThing.charAt(0).toUpperCase() + typeOfThing.slice(1); }

Mahdi

somevar.constructor.name 과 같이 somevar.constructor.name을 사용해야 합니다.

 const getVariableType = a => a.constructor.name.toLowerCase(); const d = new Date(); const res1 = getVariableType(d); // 'date' const num = 5; const res2 = getVariableType(num); // 'number' const fn = () => {}; const res3 = getVariableType(fn); // 'function' console.log(res1); // 'date' console.log(res2); // 'number' console.log(res3); // 'function'


user9563942

가능하면 constructor.name 사용하고 할 수 없으면 regex 함수를 사용하십시오.

 Function.prototype.getName = function(){ if (typeof this.name != 'undefined') return this.name; else return /function (.+)\(/.exec(this.toString())[1]; };

defrex

Agave.JSkind() 함수는 다음을 반환합니다.

  • 상속 트리에서 가장 가까운 프로토타입
  • 'null' 및 'undefined'와 같은 항상 기본 유형의 경우 기본 이름입니다.

생성 방법에 관계없이 모든 JS 개체 및 기본 요소에서 작동하며 놀라움이 없습니다.

 var kind = function(item) { var getPrototype = function(item) { return Object.prototype.toString.call(item).slice(8, -1); }; var kind, Undefined; if (item === null ) { kind = 'null'; } else { if ( item === Undefined ) { kind = 'undefined'; } else { var prototype = getPrototype(item); if ( ( prototype === 'Number' ) && isNaN(item) ) { kind = 'NaN'; } else { kind = prototype; } } } return kind; };

예:

숫자

 kind(37) === 'Number' kind(3.14) === 'Number' kind(Math.LN2) === 'Number' kind(Infinity) === 'Number' kind(Number(1)) === 'Number' kind(new Number(1)) === 'Number'

 kind(NaN) === 'NaN'

문자열

 kind('') === 'String' kind('bla') === 'String' kind(String("abc")) === 'String' kind(new String("abc")) === 'String'

부울

 kind(true) === 'Boolean' kind(false) === 'Boolean' kind(new Boolean(true)) === 'Boolean'

배열

 kind([1, 2, 4]) === 'Array' kind(new Array(1, 2, 3)) === 'Array'

사물

 kind({a:1}) === 'Object' kind(new Object()) === 'Object'

날짜

 kind(new Date()) === 'Date'

기능

 kind(function(){}) === 'Function' kind(new Function("console.log(arguments)")) === 'Function' kind(Math.sin) === 'Function'

찾으시는 주소가 없습니다

 kind(undefined) === 'undefined'

없는

 kind(null) === 'null'

mikemaccana

instanceof 연산자를 사용하여 개체가 다른 개체의 인스턴스인지 확인할 수 있지만 클래스가 없기 때문에 클래스 이름을 얻을 수 없습니다.


Greg

다음은 허용된 답변을 기반으로 한 구현입니다.

 /** * Returns the name of an object's type. * * If the input is undefined, returns "Undefined". * If the input is null, returns "Null". * If the input is a boolean, returns "Boolean". * If the input is a number, returns "Number". * If the input is a string, returns "String". * If the input is a named function or a class constructor, returns "Function". * If the input is an anonymous function, returns "AnonymousFunction". * If the input is an arrow function, returns "ArrowFunction". * If the input is a class instance, returns "Object". * * @param {Object} object an object * @return {String} the name of the object's class * @see <a href="https://stackoverflow.com/a/332429/14731">https://stackoverflow.com/a/332429/14731</a> * @see getFunctionName * @see getObjectClass */ function getTypeName(object) { const objectToString = Object.prototype.toString.call(object).slice(8, -1); if (objectToString === "Function") { const instanceToString = object.toString(); if (instanceToString.indexOf(" => ") != -1) return "ArrowFunction"; const getFunctionName = /^function\s+([^(]+)?\(/; const match = instanceToString.match(getFunctionName); if (match === null) return "AnonymousFunction"; return "Function"; } // Built-in types (eg String) or class instances return objectToString; }; /** * Returns the name of a function. * * If the input is an anonymous function, returns "". * If the input is an arrow function, returns "=>". * * @param {Function} fn a function * @return {String} the name of the function * @throws {TypeError} if {@code fn} is not a function * @see getTypeName */ function getFunctionName(fn) { try { const instanceToString = fn.toString(); if (instanceToString.indexOf(" => ") != -1) return "=>"; const getFunctionName = /^function\s+([^(]+)?\(/; const match = instanceToString.match(getFunctionName); if (match === null) { const objectToString = Object.prototype.toString.call(fn).slice(8, -1); if (objectToString === "Function") return ""; throw TypeError("object must be a Function.\n" + "Actual: " + getTypeName(fn)); } return match[1]; } catch (e) { throw TypeError("object must be a Function.\n" + "Actual: " + getTypeName(fn)); } }; /** * @param {Object} object an object * @return {String} the name of the object's class * @throws {TypeError} if {@code object} is not an Object * @see getTypeName */ function getObjectClass(object) { const getFunctionName = /^function\s+([^(]+)?\(/; const result = object.constructor.toString().match(getFunctionName)[1]; if (result === "Function") { throw TypeError("object must be an Object.\n" + "Actual: " + getTypeName(object)); } return result; }; function UserFunction() { } function UserClass() { } let anonymousFunction = function() { }; let arrowFunction = i => i + 1; console.log("getTypeName(undefined): " + getTypeName(undefined)); console.log("getTypeName(null): " + getTypeName(null)); console.log("getTypeName(true): " + getTypeName(true)); console.log("getTypeName(5): " + getTypeName(5)); console.log("getTypeName(\"text\"): " + getTypeName("text")); console.log("getTypeName(userFunction): " + getTypeName(UserFunction)); console.log("getFunctionName(userFunction): " + getFunctionName(UserFunction)); console.log("getTypeName(anonymousFunction): " + getTypeName(anonymousFunction)); console.log("getFunctionName(anonymousFunction): " + getFunctionName(anonymousFunction)); console.log("getTypeName(arrowFunction): " + getTypeName(arrowFunction)); console.log("getFunctionName(arrowFunction): " + getFunctionName(arrowFunction)); //console.log("getFunctionName(userClass): " + getFunctionName(new UserClass())); console.log("getTypeName(userClass): " + getTypeName(new UserClass())); console.log("getObjectClass(userClass): " + getObjectClass(new UserClass())); //console.log("getObjectClass(userFunction): " + getObjectClass(UserFunction)); //console.log("getObjectClass(userFunction): " + getObjectClass(anonymousFunction)); //console.log("getObjectClass(arrowFunction): " + getObjectClass(arrowFunction)); console.log("getTypeName(nativeObject): " + getTypeName(navigator.mediaDevices.getUserMedia)); console.log("getFunctionName(nativeObject): " + getFunctionName(navigator.mediaDevices.getUserMedia));

우리는 다른 선택이 없을 때만 생성자 속성을 사용합니다.


Gili

"instanceof" 연산자를 사용하여 개체가 특정 클래스의 인스턴스인지 여부를 확인할 수 있습니다. 개체 유형의 이름을 모르는 경우 해당 생성자 속성을 사용할 수 있습니다. 객체의 생성자 속성은 객체를 초기화하는 데 사용되는 함수에 대한 참조입니다. 예시:

 function Circle (x,y,radius) { this._x = x; this._y = y; this._radius = raduius; } var c1 = new Circle(10,20,5);

이제 c1.constructor는 Circle() 함수에 대한 참조입니다. typeof 연산자를 사용할 수도 typeof 연산자는 제한된 정보를 보여줍니다. 한 가지 해결책은 Object 전역 객체 toString() 예를 들어 myObject와 같은 객체가 있는 경우 toString() 메서드를 사용하여 myObject의 클래스 유형을 결정할 수 있습니다. 이것을 사용하십시오:

 Object.prototype.toString.apply(myObject);

farzad

var obj; 가 있다고 가정해 보겠습니다.

"Object", "Array" 또는 "String"과 같은 obj 유형의 이름만 원하는 경우 다음을 사용할 수 있습니다.

 Object.prototype.toString.call(obj).split(' ')[1].replace(']', '');

Big Sam

가장 가까운 것은 typeof 이지만 모든 종류의 사용자 정의 유형에 대해서만 "객체"를 반환합니다. 이에 대해서는 제이슨 번팅을 참조하십시오.

편집, Jason은 어떤 이유로 게시물을 삭제 했으므로 Object의 constructor 속성을 사용하십시오.


sblundy

상당히 간단합니다!

  • JS에서 유형을 얻는 가장 좋아하는 방법
 function getType(entity){ var x = Object.prototype.toString.call(entity) return x.split(" ")[1].split(']')[0].toLowerCase() }
  • JS에서 유형을 확인하는 가장 좋아하는 방법
 function checkType(entity, type){ return getType(entity) === type }

ZenG

누구든지 jQuery와 함께 작동하는 솔루션을 찾고 있다면 여기에 조정된 wiki 코드가 있습니다(원본은 jQuery를 중단함).

 Object.defineProperty(Object.prototype, "getClassName", { value: function() { var funcNameRegex = /function (.{1,})\(/; var results = (funcNameRegex).exec((this).constructor.toString()); return (results && results.length > 1) ? results[1] : ""; } });

Daniel Jankowski

Lodash에는 많은 isMethods가 있으므로 Lodash를 사용하는 경우 다음과 같은 믹스인이 유용할 수 있습니다.

 // Mixin for identifying a Javascript Object _.mixin({ 'identify' : function(object) { var output; var isMethods = ['isArguments', 'isArray', 'isArguments', 'isBoolean', 'isDate', 'isArguments', 'isElement', 'isError', 'isFunction', 'isNaN', 'isNull', 'isNumber', 'isPlainObject', 'isRegExp', 'isString', 'isTypedArray', 'isUndefined', 'isEmpty', 'isObject'] this.each(isMethods, function (method) { if (this[method](object)) { output = method; return false; } }.bind(this)); return output; } });

다음과 같이 작동하는 "identify"라는 메서드를 lodash에 추가합니다.

 console.log(_.identify('hello friend')); // isString

플런커: http://plnkr.co/edit/Zdr0KDtQt76Ul3KTEDSN


Guy

좋아요, 여러분 저는 몇 년 동안 이것을 위해 모든 방법을 천천히 구축해 왔습니다. 비결은 다음과 같습니다.

  1. 클래스를 생성하는 메커니즘이 있습니다.
  2. 기본 생성자에 의해 생성/생성된 모든 사용자 생성 클래스, 프리미티브 및 값을 확인하는 메커니즘이 있습니다.
  3. 위의 기능이 코드/애플리케이션/라이브러리/등을 통해 스며들도록 사용자 생성 클래스를 새로운 클래스로 확장하는 메커니즘을 갖습니다.

예를 들어(또는 내가 문제를 처리한 방법을 보려면) github에서 다음 코드를 살펴보세요. https://github.com/elycruz/sjljs/blob/master/src/sjl/sjl.js 및 검색:

classOf = , classOfIs = 및 또는 defineSubClass = (역따옴표(`) 제외).

보시다시피 기본 생성자, 사용자 정의 클래스, 기본 생성자를 사용하여 생성된 값, Null, NaN 등에 관계없이 classOf 가 항상 나에게 클래스/생성자 유형 이름을 제공하도록 강제하는 몇 가지 메커니즘이 있습니다. 모든 단일 자바스크립트 값에 대해 classOf 함수에서 고유한 유형 이름을 가져옵니다. 또한 실제 생성자를 sjl.classOfIs 에 전달하여 값의 유형 이름을 전달할 수 있을 뿐만 아니라 값의 유형을 확인할 수 있습니다! 예를 들면 다음과 같습니다.

``` // 긴 네임스페이스를 용서하세요! 한동안 사용하고 나서까지 임팩트를 전혀 몰랐어요.

 var SomeCustomClass = sjl.package.stdlib.Extendable.extend({ constructor: function SomeCustomClass () {}, // ... }), HelloIterator = sjl.ns.stdlib.Iterator.extend( function HelloIterator () {}, { /* ... methods here ... */ }, { /* ... static props/methods here ... */ } ), helloIt = new HelloIterator(); sjl.classOfIs(new SomeCustomClass(), SomeCustomClass) === true; // `true` sjl.classOfIs(helloIt, HelloIterator) === true; // `true` var someString = 'helloworld'; sjl.classOfIs(someString, String) === true; // `true` sjl.classOfIs(99, Number) === true; // true sjl.classOf(NaN) === 'NaN'; // true sjl.classOf(new Map()) === 'Map'; sjl.classOf(new Set()) === 'Set'; sjl.classOfIs([1, 2, 4], Array) === true; // `true` // etc.. // Also optionally the type you want to check against could be the type's name sjl.classOfIs(['a', 'b', 'c'], 'Array') === true; // `true`! sjl.classOfIs(helloIt, 'HelloIterator') === true; // `true`!

```

위에서 언급한 설정을 사용하는 방법에 대한 자세한 내용을 읽고 싶다면 https://github.com/elycruz/sjljs 리포지토리를 살펴보세요.

또한 주제에 대한 내용이 포함된 책: - Stoyan Stefanov의 "JavaScript Patterns". - "자바스크립트 - 최종 가이드." 데이비드 플래너건 지음. - 그리고 많은 다른 사람들.. (검색 le` 웹).

또한 여기에서 내가 말하는 기능을 빠르게 테스트할 수 있습니다. - http://sjljs.elycruz.com/0.5.18/tests/for-browser/ (또한 URL의 0.5.18 경로에는 github의 소스가 있습니다. 거기에서 node_modules 등을 뺀 것).

행복한 코딩!


elydelacruz

class.name 사용하십시오. function.name 에서도 작동합니다.

 class TestA {} console.log(TestA.name); // "TestA" function TestB() {} console.log(TestB.name); // "TestB"

qwertzguy

이 글을 읽고 상당히 잘 작동하고 테스트를 거친 간단한 솔루션을 원하는 분들을 위해:

 const getTypeName = (thing) => { const name = typeof thing if (name !== 'object') return name if (thing instanceof Error) return 'error' if (!thing) return 'null' return ({}).toString.call(thing).match(/\s([a-zA-Z]+)/)[1].toLowerCase() }

이것이 작동하는 이유에 대한 통찰력을 얻으려면 Array.isArray()에 대한 폴리필 문서를 확인 하세요. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray#polyfill


rodo

출처 : http:www.stackoverflow.com/questions/332422/get-the-name-of-an-objects-type

반응형