var str = new String("hello world");
console.log(str instanceof String);//true
console.log(String instanceof Function);//true
console.log(str instanceof Function);//false
第三次输出为什么会返回false呢
Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
instanceof 到底比较的什么?
instanceof又叫关系运算符,可以用来判断某个构造函数的prototype属性是否存在另外一个要检测对象的原型链上
原代码
简单的介绍
1、每一个js对象都有一个proto属性 (标准表示[[prototype]]),proto是普通对象的隐式属性,在实例化的时候,会指向prototype所指的对象;对象是没有prototype属性的,prototype则是属于构造函数的属性,即
2、通过proto属性的串联构建了一个对象的原型访问链,起点为一个具体的对象,终点在Object.prototype,即
指向关系
str的原型链上没有Function.prototype,所以返回false
instanceof这个运算符的名字没起好,带有很强的误导性。仅从字面理解,它好像是检查一个对象是否为某个类型的实例对象,然而a instanceof b真正的语义是检查 b.prototype 是否在 a 的原型链上,仅此而已。str 的原型链:
String 的原型链:
Function.protype 不在 str 的原型链上,所以 str instanceof Function 返回 false
var str = new String("hello world");
console.log(str instanceof String);//true
console.log(String instanceof Function);//true
console.log(str instanceof Function);//false