javascript面向对象 - Javascript中一个关于instanceof的问题
PHP中文网
PHP中文网 2017-04-10 16:01:11
[JavaScript讨论组]
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呢

PHP中文网
PHP中文网

认证0级讲师

全部回复(3)
伊谢尔伦

instanceof 到底比较的什么?

instanceof又叫关系运算符,可以用来判断某个构造函数的prototype属性是否存在另外一个要检测对象的原型链上

原代码

var str = new String("hello world");
console.log(str instanceof String);//true
console.log(String instanceof Function);//true
console.log(str instanceof Function);//false

简单的介绍

1、每一个js对象都有一个proto属性 (标准表示[[prototype]]),proto是普通对象的隐式属性,在实例化的时候,会指向prototype所指的对象;对象是没有prototype属性的,prototype则是属于构造函数的属性,即

console.log(str.__proto__ === String.prototype); //true

2、通过proto属性的串联构建了一个对象的原型访问链,起点为一个具体的对象,终点在Object.prototype,即

console.log( Object.prototype.__proto__ === null ); //true

指向关系

//表达式一的指向
console.log(str.__proto__ === String.prototype);//true
console.log(str instanceof String); //true

//表达式二的指向
console.log(String.__proto__ === Function.prototype);//true
console.log(String instanceof Function);//true

//表达式三的指向
console.log(str.__proto__ === String.prototype);//true
console.log(str.__proto__.__proto__ === String.prototype.__proto__);//true
console.log(str.__proto__.__proto__ === Object.prototype);//true
console.log(str.__proto__.__proto__.__proto__ === null);//true
console.log(str instanceof Object);//true
console.log(str instanceof Function);//false

str的原型链上没有Function.prototype,所以返回false

PHP中文网

instanceof 这个运算符的名字没起好,带有很强的误导性。仅从字面理解,它好像是检查一个对象是否为某个类型的实例对象,然而 a instanceof b 真正的语义是检查 b.prototype 是否在 a 的原型链上,仅此而已。

str 的原型链:

 str ---> String.prototype ---> Object.prototype

String 的原型链:

String ---> Function.prototype ---> Object.prototype

Function.protype 不在 str 的原型链上,所以 str instanceof Function 返回 false

PHP中文网

var str = new String("hello world");
console.log(str instanceof String);//true
console.log(String instanceof Function);//true
console.log(str instanceof Function);//false

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号