第88天 判断instanceof的结果并解释原因 [代码] ``` function test(){ return test; } new test() instanceof test; ```
Activity
ghost commentedon Jul 13, 2019
如果函数明确返回值,那么new
运算符的结果将是这个值。new
运算符的结果将是这个值。- 感谢 @xxf1996 指正test instanceof test
。instanceof
运算符将检测右端值的prototype
属性是否在左端值的原型链([[Prototype]]
属性)上;[[Prototype]]
的[[Prototype]]
,…),直到找遍左端值的整个原型链。test
是一个Function
,故它的原型链为:test.prototype
出现,所以test
并不是test
的一个实例。instanceof
运算符返回false
。xxf1996 commentedon Jul 14, 2019
@t532 有一点需要指正:
实际上应该是如果函数返回的值是引用类型(对象)的值时,
new
运算符将返回这个值。详情可以参考《你不知道的js(上卷)》——2.2.4小节。smile-2008 commentedon Mar 9, 2021
mohaixiao commentedon Jun 21, 2022
我的答案
因为test函数返回了自身不是空对象,test函数也是一个对象,所以new test()返回值是test函数自身。
instanceof 运算符将检测右端值的 prototype 属性是否在左端值的原型链([[Prototype]] 属性)上;
如果不在,则向上查找([[Prototype]] 的 [[Prototype]],…),直到找遍左端值的整个原型链。
本题变为了test instanceof test 然而test函数对象的原型链是Function.prototype -> Object.prototype -> null,没有构造函数test的prototype属性在上面。也就是原型链上没有test.prototype。