JavaScript: 'typeof' 运算符没有 return 正确的类类型

JavaScript: 'typeof' operator does not return correct classtype

我可能犯了一个大错误。目前我正在尝试声明两个 classes,如下所示。但在这两种情况下,'typeof' 都会返回 'object'。在 JavaScript 中声明 class 的正确过程是什么,以便我们可以通过 'typeof' 运算符获得正确的 class 名称。

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);

提前致谢。

您必须检查 instanceof 而不是 typeof

typeof 只会给你对象数据类型。

console.log(a instanceof Furniture);
console.log(b instanceof Chair);

参考How do I get the name of an object's type in JavaScript? 上面的 SO 显示了查找构造函数名称的各种方法。

这是正确的行为。 Mozilla developer network 有用 table,结果描述为 typeof 运算符:

我认为稍微了解一下 js 会非常有用。 Javascript 看起来很简单的语言。这不是真的。这是一个棘手的问题。

这对你有用

    var toType = function(obj) {
        return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
   }

var b = new Chair();

console.log(toType(b));  // Chair

访问此处
typeOf Does not return correct class type