gpt4 book ai didi

JavaScript: 'typeof' 运算符未返回正确的类类型

转载 作者:行者123 更新时间:2023-11-28 15:24:34 24 4
gpt4 key购买 nike

也许我犯了一个巨大的错误。目前我正在尝试声明两个类,如下所示。但在这两种情况下,“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);

提前致谢。

最佳答案

您必须检查 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 显示了查找构造函数名称的各种方法。

关于JavaScript: 'typeof' 运算符未返回正确的类类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29602693/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com