【发布时间】:2015-06-18 14:35:42
【问题描述】:
我可能犯了一个巨大的错误。目前我正在尝试声明两个类,如下所示。但在这两种情况下,“typeof”都返回“object”。在 JavaScript 中声明一个类的正确过程是什么,这样我们就可以通过 'typeof' 运算符获得正确的类名。
var Furniture = function(legs){
this.legs = legs;
};
Furniture.prototype.getLegs = function(){ return this.legs; };
var Chair = function(){
Furniture.call(this, 4);
};
Chair.prototype = Object.create(Furniture.prototype);
var a = new Furniture(12);
var b = new Chair();
console.log(typeof a);
console.log(typeof b);
提前致谢。
【问题讨论】:
-
typeof 不返回类名,而是返回类型名。如果要提取家具或椅子,请使用 instanceof。
-
见这个:stackoverflow.com/q/332422/1207195。例如:
a.constructor.name和b.constructor.name。 -
我不知道,为什么这个问题被否决了。我可能不知道 JavaScript 的复杂概念。那么,我不能向社区提出这个问题吗?我认为这很侮辱人。
标签: javascript class oop inheritance typeof