Javascript中一个关于instanceof的问题

varstr=newString("helloworld");
console.log(strinstanceofString);//true
console.log(StringinstanceofFunction);//true
console.log(strinstanceofFunction);//false
第三次输出为什么会返回false呢
墨色风雨
浏览 472回答 2
2回答

猛跑小猪

instanceof到底比较的什么?instanceof又叫关系运算符,可以用来判断某个构造函数的prototype属性是否存在另外一个要检测对象的原型链上原代码varstr=newString("helloworld");console.log(strinstanceofString);//trueconsole.log(StringinstanceofFunction);//trueconsole.log(strinstanceofFunction);//false简单的介绍1、每一个js对象都有一个proto属性(标准表示[[prototype]]),proto是普通对象的隐式属性,在实例化的时候,会指向prototype所指的对象;对象是没有prototype属性的,prototype则是属于构造函数的属性,即console.log(str.__proto__===String.prototype);//true2、通过proto属性的串联构建了一个对象的原型访问链,起点为一个具体的对象,终点在Object.prototype,即console.log(Object.prototype.__proto__===null);//true指向关系//表达式一的指向console.log(str.__proto__===String.prototype);//trueconsole.log(strinstanceofString);//true//表达式二的指向console.log(String.__proto__===Function.prototype);//trueconsole.log(StringinstanceofFunction);//true//表达式三的指向console.log(str.__proto__===String.prototype);//trueconsole.log(str.__proto__.__proto__===String.prototype.__proto__);//trueconsole.log(str.__proto__.__proto__===Object.prototype);//trueconsole.log(str.__proto__.__proto__.__proto__===null);//trueconsole.log(strinstanceofObject);//trueconsole.log(strinstanceofFunction);//falsestr的原型链上没有Function.prototype,所以返回false

慕神8447489

instanceof这个运算符的名字没起好,带有很强的误导性。仅从字面理解,它好像是检查一个对象是否为某个类型的实例对象,然而ainstanceofb真正的语义是检查b.prototype是否在a的原型链上,仅此而已。str的原型链:str--->String.prototype--->Object.prototypeString的原型链:String--->Function.prototype--->Object.prototypeFunction.protype不在str的原型链上,所以strinstanceofFunction返回false
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript