为了账号安全,请及时绑定邮箱和手机立即绑定

Javascript中一个关于instanceof的问题

Javascript中一个关于instanceof的问题

墨色风雨 2019-04-19 16:30:07
varstr=newString("helloworld");console.log(strinstanceofString);//trueconsole.log(StringinstanceofFunction);//trueconsole.log(strinstanceofFunction);//false第三次输出为什么会返回false呢
查看完整描述

2 回答

?
猛跑小猪

TA贡献1858条经验 获得超8个赞

instanceof到底比较的什么?
instanceof又叫关系运算符,可以用来判断某个构造函数的prototype属性是否存在另外一个要检测对象的原型链上
原代码
varstr=newString("helloworld");
console.log(strinstanceofString);//true
console.log(StringinstanceofFunction);//true
console.log(strinstanceofFunction);//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(strinstanceofString);//true
//表达式二的指向
console.log(String.__proto__===Function.prototype);//true
console.log(StringinstanceofFunction);//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(strinstanceofObject);//true
console.log(strinstanceofFunction);//false
str的原型链上没有Function.prototype,所以返回false
                            
查看完整回答
反对 回复 2019-04-19
?
慕神8447489

TA贡献1780条经验 获得超1个赞

instanceof这个运算符的名字没起好,带有很强的误导性。仅从字面理解,它好像是检查一个对象是否为某个类型的实例对象,然而ainstanceofb真正的语义是检查b.prototype是否在a的原型链上,仅此而已。
str的原型链:
str--->String.prototype--->Object.prototype
String的原型链:
String--->Function.prototype--->Object.prototype
Function.protype不在str的原型链上,所以strinstanceofFunction返回false
                            
查看完整回答
反对 回复 2019-04-19
  • 2 回答
  • 0 关注
  • 471 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信