js中判断一个对象是不是另外一个对象的子类

本文介绍了如何使用JavaScript中的instanceof操作符来判断一个变量是否为数组类型。通过实例演示了其基本用法,返回布尔值以确定变量类型。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

arr = [1,2,3];
if(arr instanceof Array){
document.write("arr 是一个数组");
} else {
document.write("arr 不是一个数组");
}

 

 

可通过 instanceof 操作符来判断对象的具体类型,语法格式:

var result = objectName instanceof objectType

返回布尔值,如果是指定类型返回 true,否则返回 false。测试如下:

arr 是一个数组

转载于:https://www.cnblogs.com/xiaohuihui1215/p/10307958.html

### 面向对象程序设计期末作业示例 #### 创建基类 `Person` 为了展示面向对象编程的核心概念,下面定义了一个基本的`Person`类作为其他家庭成员类的基础。 ```javascript class Person { constructor(name, age) { this.name = name; this.age = age; } introduce() { console.log(`Hello! My name is ${this.name} and I am ${this.age} years old.`); } } ``` 此代码片段展示了如何通过构造函数初始化属性以及定义实例方法来执行特定行为[^1]。 #### 扩展自定义子类 基于上述基础,可以进一步扩展出不同的角色类别: ```javascript // 定义 Father 类继承于 Person class Father extends Person { constructor(name, age, occupation) { super(name, age); this.occupation = occupation; // 新增职业字段 } work() { // 添加工作方法 console.log(`${this.name} works as a ${this.occupation}.`); } } // 同样方式可实现 Mother 和 Son 等其它角色... ``` 这里利用了JavaScript ES6中的`extends`关键字实现了对已有功能的良好复用并增加了新的特性支持[^4]。 #### 实例化与类型判断 当创建具体的人物实例时,能够方便地调用其所属类的方法,并可通过适当的方式验证这些实体的确切身份。 ```javascript let fatherInstance = new Father('John Doe', 40, 'Engineer'); fatherInstance.introduce(); // 调用了来自父级 class 的通用介绍逻辑 fatherInstance.work(); console.log(fatherInstance instanceof Father); // true console.log(fatherInstance instanceof Person); // true console.log(fatherInstance.constructor === Father); // true ``` 这段脚本不仅体现了多态性的优势——即不同类型的对象可以通过相同的接口被处理,同时也强调了使用`instanceof`而非仅依赖于`.constructor`来进行更加可靠的类型检查的重要性[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值