我创建了一个JavaScript对象,但如何确定该对象的类?
我想要类似于Java的. getclass()方法的东西。
我创建了一个JavaScript对象,但如何确定该对象的类?
我想要类似于Java的. getclass()方法的东西。
当前回答
你也可以这样做
Hello { 构造函数(){ } } 函数isClass (func) { 返回typeof func === 'function' && /^class\s/.test(function .prototype. tostring .call(func)) } console.log (isClass(你好))
这将告诉您输入是否是类
其他回答
问题似乎已经回答了,但OP想要访问和对象的类,就像我们在Java中所做的那样,选择的答案是不够的(imho)。
通过下面的解释,我们可以得到一个对象的类(实际上在javascript中称为prototype)。
var arr = new Array('red', 'green', 'blue');
var arr2 = new Array('white', 'black', 'orange');
你可以像这样添加属性:
Object.defineProperty(arr,'last', {
get: function(){
return this[this.length -1];
}
});
console.log(arr.last) // blue
但是.last属性将只对从Array原型实例化的'arr'对象可用。因此,为了使.last属性对所有从Array prototype实例化的对象可用,我们必须为Array prototype定义.last属性:
Object.defineProperty(Array.prototype,'last', {
get: function(){
return this[this.length -1];
}
});
console.log(arr.last) // blue
console.log(arr2.last) // orange
这里的问题是,你必须知道“arr”和“arr2”变量属于哪种对象类型(原型)!换句话说,如果您不知道'arr'对象的类类型(原型),那么您将无法为它们定义属性。在上面的例子中,我们知道arr是Array对象的实例,这就是为什么我们使用Array。prototype为Array定义一个属性。但如果我们不知道“arr”的类(原型)呢?
Object.defineProperty(arr.__proto__,'last2', {
get: function(){
return this[this.length -1];
}
});
console.log(arr.last) // blue
console.log(arr2.last) // orange
正如你所看到的,在不知道'arr'是一个数组的情况下,我们可以添加一个新属性,只需使用'arr.__proto__'引用'arr'的类即可。
我们访问了'arr'的原型,但不知道它是Array的实例,我认为这是OP要求的。
Javascript是一种无类语言:它不像Java那样有静态定义类行为的类。JavaScript使用原型而不是类来定义对象属性,包括方法和继承。用JavaScript中的原型模拟许多基于类的特性是可能的。
要获得“伪类”,可以通过获取构造函数
obj.constructor
假设在你进行继承时构造函数被正确地设置了——就像这样:
Dog.prototype = new Animal();
Dog.prototype.constructor = Dog;
这两行,加上:
var woofie = new Dog()
会做出伍菲。构造器指向狗。注意,Dog是一个构造函数,是一个function对象。但是你可以这样做,如果。构造函数=== 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,包括IE 9或IE 10 RTM。
getClass()函数使用constructor.prototype.name
我找到了一种方法来访问类,比上面的一些解决方案要干净得多;在这儿。
function getClass(obj) {
// if the type is not an object return the type
if((let type = typeof obj) !== 'object') return type;
//otherwise, access the class using obj.constructor.name
else return obj.constructor.name;
}
它是如何工作的
构造函数有一个名为name access的属性,它将为您提供类名。
更简洁的代码版本:
function getClass(obj) {
// if the type is not an object return the type
let type = typeof obj
if((type !== 'object')) {
return type;
} else { //otherwise, access the class using obj.constructor.name
return obj.constructor.name;
}
}
我建议使用Object.prototype.constructor.name:
Object.defineProperty(Object.prototype, "getClass", {
value: function() {
return this.constructor.name;
}
});
var x = new DOMParser();
console.log(x.getClass()); // `DOMParser'
var y = new Error("");
console.log(y.getClass()); // `Error'