0
点赞
收藏
分享

微信扫一扫

JavaScript-instanceof关键字

什么是 instanceof 关键字

​instanceof​​​ 用于判断 ​​"对象"​​ 是否是指定构造函数的 "实例"。

先来看如下这一段代码,利用 instanceof 关键字来看看结果。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript-instanceof关键字</title>
<script>
class Person {
name = "BNTang";
}

let p = new Person();
console.log(p instanceof Person);

class Cat {
name = "mm";
}

let c = new Cat();
console.log(c instanceof Person);
</script>
</head>
<body>
</body>
</html>

JavaScript-instanceof关键字_javascript

运行结果如上,实例对象只有是指定对应的构造函数创建出来的才会返回 ​​true​​​ 否则为 ​​false​​。

instanceof 注意点

只要构造函数的原型对象出现在实例对象的原型链中都会返回 ​​true​​。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript-instanceof关键字</title>
<script>
function Person(name) {
this.name = name;
}

function Student(name, score) {
Person.call(this, name);
this.score = score;
}

Student.prototype = new Person();
Student.prototype.constructor = Student;

let stu = new Student();
console.log(stu instanceof Person);
</script>
</head>
<body>
</body>
</html>

JavaScript-instanceof关键字_javascript_02




举报

相关推荐

0 条评论