为JavaScript中的所有类型的变量定义原型

问题描述 投票:0回答:1

我已经用JavaScript编写了以下代码

Object.prototype.is_string = function () {
 return typeof this === 'string' || this instanceof String;
}

当我编写下面的代码时没有问题:

let item = 'string item';
console.log(item.is_string()); // true

但是当我编写下面的代码时,出现错误

let item = null;
console.log(item.is_string());

enter image description here

如何为所有变量类型定义此方法?

javascript prototype
1个回答
0
投票

在JavaScript中,图元(图元值,图元数据类型)是不是对象且没有方法的数据。有7种原始数据类型:字符串,数字,bigint,布尔值,null,未定义和符号。

Primitive

基本上,即使typoef null返回object,它也是NOT对象,但是原始值。在您的代码中,还要检查null值。

© www.soinside.com 2019 - 2024. All rights reserved.