개체 유형의 이름을 가져옵니다.
자바와 동등한 JavaScript가 있습니까?class.getName()
?
class.getName()
아니요.
ES2015 업데이트: 이름은 입니다.이름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()
생성자 이름을 문자열로 반환합니다.는 이것을 것 tested i에서 해 본 적이 있다.FF3
and 그리고.IE7
, , I can't speak for other implementations., 다른 실장은 말할 수 없습니다.
이를 원하지 않는 경우 JavaScript에서 유형을 결정하는 다양한 방법에 대해 설명합니다.
저는 최근에 조금 더 자세히 업데이트 했습니다만, 그 정도는 아닙니다.수정 환영...
용 방 usingconstructor
재산...속성...
모 모든 든object
has a value for its 가치가 있다constructor
property, but depending on how that 하지만 그 방법에 따라서는object
그 가치를 가진 것과 마찬가지로 구성되었으며 유용하지 않을 수 있으며 유용하지 않을 수도 있습니다.이 값을 사용하여 수행할 작업과 함께 구성되었습니다. 도움이 될 수도 있고 그렇지 않을 수도 있습니다.
Generally speaking, you can use the 일반적으로는, 다음과 같은 것을 사용할 수 있습니다.constructor
개체 유형을 테스트하려면 다음과 같은 개체 유형을 테스트하기 위한 속성다음과 같이 오브젝트 유형을 테스트하는 속성:
var myArray = [1,2,3];
(myArray.constructor == Array); // true
따라서 대부분의 니즈에 충분히 대응할 수 있습니다.그 말은...
주의사항
대부분의 경우 전혀 작동하지 않습니다.
이 패턴은 깨졌지만 매우 일반적입니다.
function Thingy() {
}
Thingy.prototype = {
method1: function() {
},
method2: function() {
}
};
Objects
constructed via 경유로 구축되다new Thingy
will have a 을 가질 것이다.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
자산, 그 중 일부는 흥미롭고 다른 일부는 그다지 많지 않습니다.현재로서는, 이 논의와는 관련이 없기 때문에, 그러한 용도를 조사하지 않습니다.
크로스 프레임과 크로스 윈도우를 사용할 수 없습니다.
「」를 사용합니다..constructor
는, 다른 을 체크할 때에 .window
iframe을 사용하다 유형마다 입니다.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
리터럴은 포장을 해야 합니다.Object
★★★★★★★★★★★★★★의 순서로instanceof
을 하다
new Number(3) instanceof Number // true
.constructor
는 리터럴 가 잘 .왜냐하면.
은 리터럴을 의 오브젝트 .
3..constructor === Number // true
'abc'.constructor === String // true
true.constructor === Boolean // true
왜 3에 점이 두 개야?Javascript는 첫 번째 점을 소수점으로 해석하기 때문입니다.
크로스 프레임과 크로스 윈도우를 사용할 수 없습니다.
instanceof
할 수 . 같은 , , 른 、 른 、 、 also 、 also 、 also 、 also 、 also 、 also also also also also also 。같은 이유로constructor
속성 체크
「 」의 name
의 of의 constructor
★★★★★★★★★★★…
대부분의 경우 전혀 작동하지 않음
다시 한 번 말씀드리지만, 위 내용을 참조하십시오.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.protype.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);
}
활자 이름만 따다
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
유용성도 중요하지만, 현재 이 논의와 크게 관련이 있다고는 생각하지 않습니다.
Jason Bunting의 답변은 나에게 필요한 것을 찾을 수 있는 충분한 단서를 주었다.
<<Object instance>>.constructor.name
예를 들어 다음과 같은 코드입니다.
function MyObject() {}
var myInstance = new MyObject();
myInstance.constructor.name
"MyObject"
.
내가 쓰는 작은 속임수:
function Square(){
this.className = "Square";
this.corners = 4;
}
var MySquare = new Square();
console.log(MySquare.className); // "Square"
갱신하다
정확히 말하면, OP는 특정 오브젝트의 컨스트럭터명을 취득하는 함수를 요구한 것 같습니다. Javascript 해해관관 in in in in in in object
는 타입이 없지만 그 자체가 타입입니다.그러나 개체마다 생성자가 다를 수 있습니다.
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가 링크한 블로그 게시물에는 그것을 하는 방법에 대한 좋은 예가 포함되어 있습니다.즉, 오브젝트 프로토타입을 확장함으로써:
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
Object.protype.toString 사용
이 투고에서 자세히 설명한 바와 같이 Object.protype.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]).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
여기에 사례의 단점을 해결하기 위해 제가 생각해낸 해결책이 있습니다.크로스 윈도우나 크로스 프레임에서 오브젝트의 타입을 체크할 수 있어 원시 타입에 문제가 없습니다.
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
type 인수는 컨스트럭터를 반환하는 콜백 함수일 수도 있습니다.콜백 함수는 지정된 객체의 창인1개의 파라미터를 수신합니다.
예:
//"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가 반환됩니다.
사실 비슷한 걸 찾다가 이런 질문을 하게 됐어요.타입을 얻는 방법은 다음과 같습니다.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);
}
하면 됩니다.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'
constructor.name
할 수 있을 때, 그리고 내가 할 수 없을 때 regex가 작동합니다.
Function.prototype.getName = function(){
if (typeof this.name != 'undefined')
return this.name;
else
return /function (.+)\(/.exec(this.toString())[1];
};
Agave의 kind() 함수입니다.JS는 다음을 반환합니다.
- 유전수에서 가장 가까운 원형
- 원어민 이름인 'supervisor'나 'supervisor'와 같이 항상 붙어있는 글자의 경우.
생성된 방법에 관계없이 모든 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'
NaN
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'
/**
* Describes the type of a variable.
*/
class VariableType
{
type;
name;
/**
* Creates a new VariableType.
*
* @param {"undefined" | "null" | "boolean" | "number" | "bigint" | "array" | "string" | "symbol" |
* "function" | "class" | "object"} type the name of the type
* @param {null | string} [name = null] the name of the type (the function or class name)
* @throws {RangeError} if neither <code>type</code> or <code>name</code> are set. If <code>type</code>
* does not have a name (e.g. "number" or "array") but <code>name</code> is set.
*/
constructor(type, name = null)
{
switch (type)
{
case "undefined":
case "null":
case "boolean" :
case "number" :
case "bigint":
case "array":
case "string":
case "symbol":
if (name !== null)
throw new RangeError(type + " may not have a name");
}
this.type = type;
this.name = name;
}
/**
* @return {string} the string representation of this object
*/
toString()
{
let result;
switch (this.type)
{
case "function":
case "class":
{
result = "a ";
break;
}
case "object":
{
result = "an ";
break;
}
default:
return this.type;
}
result += this.type;
if (this.name !== null)
result += " named " + this.name;
return result;
}
}
const functionNamePattern = /^function\s+([^(]+)?\(/;
const classNamePattern = /^class(\s+[^{]+)?{/;
/**
* Returns the type information of a value.
*
* <ul>
* <li>If the input is undefined, returns <code>(type="undefined", name=null)</code>.</li>
* <li>If the input is null, returns <code>(type="null", name=null)</code>.</li>
* <li>If the input is a primitive boolean, returns <code>(type="boolean", name=null)</code>.</li>
* <li>If the input is a primitive number, returns <code>(type="number", name=null)</code>.</li>
* <li>If the input is a primitive or wrapper bigint, returns
* <code>(type="bigint", name=null)</code>.</li>
* <li>If the input is an array, returns <code>(type="array", name=null)</code>.</li>
* <li>If the input is a primitive string, returns <code>(type="string", name=null)</code>.</li>
* <li>If the input is a primitive symbol, returns <code>(type="symbol", null)</code>.</li>
* <li>If the input is a function, returns <code>(type="function", name=the function name)</code>. If the
* input is an arrow or anonymous function, its name is <code>null</code>.</li>
* <li>If the input is a function, returns <code>(type="function", name=the function name)</code>.</li>
* <li>If the input is a class, returns <code>(type="class", name=the name of the class)</code>.
* <li>If the input is an object, returns
* <code>(type="object", name=the name of the object's class)</code>.
* </li>
* </ul>
*
* Please note that built-in types (such as <code>Object</code>, <code>String</code> or <code>Number</code>)
* may return type <code>function</code> instead of <code>class</code>.
*
* @param {object} value a value
* @return {VariableType} <code>value</code>'s type
* @see <a href="http://stackoverflow.com/a/332429/14731">http://stackoverflow.com/a/332429/14731</a>
* @see isPrimitive
*/
function getTypeInfo(value)
{
if (value === null)
return new VariableType("null");
const typeOfValue = typeof (value);
const isPrimitive = typeOfValue !== "function" && typeOfValue !== "object";
if (isPrimitive)
return new VariableType(typeOfValue);
const objectToString = Object.prototype.toString.call(value).slice(8, -1);
// eslint-disable-next-line @typescript-eslint/ban-types
const valueToString = value.toString();
if (objectToString === "Function")
{
// A function or a constructor
const indexOfArrow = valueToString.indexOf("=>");
const indexOfBody = valueToString.indexOf("{");
if (indexOfArrow !== -1 && (indexOfBody === -1 || indexOfArrow < indexOfBody))
{
// Arrow function
return new VariableType("function");
}
// Anonymous and named functions
const functionName = functionNamePattern.exec(valueToString);
if (functionName !== null && typeof (functionName[1]) !== "undefined")
{
// Found a named function or class constructor
return new VariableType("function", functionName[1].trim());
}
const className = classNamePattern.exec(valueToString);
if (className !== null && typeof (className[1]) !== "undefined")
{
// When running under ES6+
return new VariableType("class", className[1].trim());
}
// Anonymous function
return new VariableType("function");
}
if (objectToString === "Array")
return new VariableType("array");
const classInfo = getTypeInfo(value.constructor);
return new VariableType("object", classInfo.name);
}
function UserFunction()
{
}
function UserClass()
{
}
let anonymousFunction = function()
{
};
let arrowFunction = i => i + 1;
console.log("getTypeInfo(undefined): " + getTypeInfo(undefined));
console.log("getTypeInfo(null): " + getTypeInfo(null));
console.log("getTypeInfo(true): " + getTypeInfo(true));
console.log("getTypeInfo(5): " + getTypeInfo(5));
console.log("getTypeInfo(\"text\"): " + getTypeInfo("text"));
console.log("getTypeInfo(userFunction): " + getTypeInfo(UserFunction));
console.log("getTypeInfo(anonymousFunction): " + getTypeInfo(anonymousFunction));
console.log("getTypeInfo(arrowFunction): " + getTypeInfo(arrowFunction));
console.log("getTypeInfo(userObject): " + getTypeInfo(new UserClass()));
console.log("getTypeInfo(nativeObject): " + getTypeInfo(navigator.mediaDevices.getUserMedia));
다른 선택이 없을 때만 컨스트럭터 속성을 사용합니다.
연산자를 사용하여 객체가 다른 인스턴스의 인스턴스인지 확인할 수 있지만 클래스가 없으므로 클래스 이름을 가져올 수 없습니다.
"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
이치노해결 중 는 '사용하는 방법'을하는 것입니다.toString()
myObject를 사용할 수 .toString()
myObject .★★★★★★★★★★★★★★★★★★:
Object.prototype.toString.apply(myObject);
를 들어, '우리'가 있다고 .var obj;
"Object", "Array" 또는 "String"과 같은 obj 유형의 이름만 원하는 경우 다음을 사용할 수 있습니다.
Object.prototype.toString.call(obj).split(' ')[1].replace(']', '');
가장 가까운 값은 입니다. 단, 모든 종류의 사용자 지정 유형에 대해 "개체"만 반환됩니다.Jason Bunting을 참조하십시오.
제이슨이 어떤 글을 의 '오브젝트 '오브젝트', '오브젝트', '오브젝트', '오브젝트', '오브젝트', '오브젝트', '오브젝트', '오브젝트', '오브젝트'를 합니다.constructor
★★★★★★★★★★★★★★★★★★.
이 글을 읽고, 매우 잘 동작하고, 테스트를 마친 심플한 솔루션을 찾고 있는 분들을 위해:
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()의 폴리필 메뉴얼을 참조해 주세요.
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] : "";
}
});
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;
}
});
Lodash에 "identify"라는 메서드를 추가하여 다음과 같이 작동합니다.
console.log(_.identify('hello friend')); // isString
Pluker: http://plnkr.co/edit/Zdr0KDtQt76Ul3KTEDSN
자, 여러분, 저는 몇 년 동안 이것을 위한 모든 캐치 방법을 천천히 만들고 있어요. lol!비결은 다음과 같습니다.
- 클래스를 만드는 메커니즘이 있습니다.
- 네이티브 컨스트럭터에 의해 작성/생성된 모든 사용자 생성 클래스, 기본 요소 및 값을 체크하는 메커니즘이 있습니다.
- 위의 기능이 코드/어플리케이션/라이브러리 등을 통해 침투하도록 사용자가 작성한 클래스를 새로운 클래스로 확장하는 메커니즘이 있습니다.
예를 들어 (또는 이 문제에 대한 대처 방법을 참조하기 위해) github의 다음 코드를 참조하여 다음 코드를 검색합니다.https://github.com/elycruz/sjljs/blob/master/src/sjl/sjl.js
classOf =
,classOfIs =
, , , " " "defineSubClass =
( 틱 ( (없 )
, 하기 위한 이 몇 가지 .classOf
원시, 사용자 정의 클래스, 네이티브 생성자를 사용하여 만든 값, Null, NaN 등에 관계없이 항상 클래스/컨스트럭터 유형 이름을 부여합니다.모든 javascript 값에 대해 고유한 유형 이름을 얻습니다.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에서 확인하시기 바랍니다.
또한 스토얀 스테파노프의 "자바스크립트 패턴" - 데이비드 플래너건의 "자바스크립트 - 최종 가이드" 등 다양한 주제에 대한 내용을 담은 책도 있습니다.(웹 검색).
또한 여기서 설명하는 기능을 빠르게 테스트할 수 있습니다.- http://sjljs.elycruz.com/0.5.18/tests/for-browser/ (또한 URL의 0.5.18 경로에는 github에서 node_module 등을 뺀 소스가 있습니다).
해피 코딩!
매우 심플!
- 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
}
class.name
쓸 수 요. , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , .function.name
.
class TestA {}
console.log(TestA.name); // "TestA"
function TestB() {}
console.log(TestB.name); // "TestB"
언급URL : https://stackoverflow.com/questions/332422/get-the-name-of-an-objects-type
'programing' 카테고리의 다른 글
mysql이 재시작되지 않음 (0) | 2022.10.27 |
---|---|
멀티바이트 문자 인코딩용 ucfirst() 함수 (0) | 2022.10.27 |
org.w3c.dom을 변환하려면 어떻게 해야 하나요?개체를 문자열에 문서화하시겠습니까? (0) | 2022.10.27 |
Python에서 알려진 수의 요소로 목록 초기화 (0) | 2022.10.27 |
문자열 배열을 java.util로 변환하고 있습니다.목록. (0) | 2022.10.27 |