Skip to content

[js] 第88天 判断instanceof的结果并解释原因 [代码] #609

Open
@haizhilin2013

Description

@haizhilin2013
Collaborator

第88天 判断instanceof的结果并解释原因 [代码]

    function test(){ 
        return test; 
    } 
    new test() instanceof test;

Activity

ghost

ghost commented on Jul 13, 2019

@ghost
  • 如果函数明确返回值,那么 new 运算符的结果将是这个值。
  • 如果函数明确返回 non-primitive 值,那么 new 运算符的结果将是这个值。- 感谢 @xxf1996 指正
  • 所以,原表达式相当于:test instanceof test

  • instanceof 运算符将检测右端值的 prototype 属性是否在左端值的原型链([[Prototype]] 属性)上;
  • 如果不在,则向上查找([[Prototype]][[Prototype]],…),直到找遍左端值的整个原型链。

注:[[Prototype]] 属性可以通过 Object.getPrototypeOf(obj) 函数获得,


  • 左端值 test 是一个 Function,故它的原型链为:
    Function.prototype -> Object.prototype -> null
  • 可以看到,原型链上没有 test.prototype 出现,所以 test 并不是 test 的一个实例。
  • 所以 instanceof 运算符返回 false
xxf1996

xxf1996 commented on Jul 14, 2019

@xxf1996

@t532 有一点需要指正:

如果函数明确返回值,那么 new 运算符的结果将是这个值。

实际上应该是如果函数返回的值是引用类型(对象)的值时,new运算符将返回这个值。详情可以参考《你不知道的js(上卷)》——2.2.4小节。

smile-2008

smile-2008 commented on Mar 9, 2021

@smile-2008
  • 如果函数明确返回值,那么 new 运算符的结果将是这个值。

  • 如果函数明确返回 non-primitive 值,那么 new 运算符的结果将是这个值。- 感谢 @xxf1996 指正

  • 所以,原表达式相当于:test instanceof test

  • instanceof 运算符将检测右端值的 prototype 属性是否在左端值的原型链([[Prototype]] 属性)上;

  • 如果不在,则向上查找([[Prototype]][[Prototype]],…),直到找遍左端值的整个原型链。

注:[[Prototype]] 属性可以通过 Object.getPrototypeOf(obj) 函数获得,

  • 左端值 test 是一个 Function,故它的原型链为:
    Function.prototype -> Object.prototype -> null
  • 可以看到,原型链上没有 test.prototype 出现,所以 test 并不是 test 的一个实例。
  • 所以 instanceof 运算符返回 false
mohaixiao

mohaixiao commented on Jun 21, 2022

@mohaixiao

我的答案

  1. 判断new test() 返回值
    因为test函数返回了自身不是空对象,test函数也是一个对象,所以new test()返回值是test函数自身。
  2. 判断返回对象的原型链上是否有构造函数test的原生对象。
    instanceof 运算符将检测右端值的 prototype 属性是否在左端值的原型链([[Prototype]] 属性)上;
    如果不在,则向上查找([[Prototype]] 的 [[Prototype]],…),直到找遍左端值的整个原型链。
    本题变为了test instanceof test 然而test函数对象的原型链是Function.prototype -> Object.prototype -> null,没有构造函数test的prototype属性在上面。也就是原型链上没有test.prototype。
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    jsJavaScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @smile-2008@haizhilin2013@xxf1996@mohaixiao

        Issue actions

          [js] 第88天 判断instanceof的结果并解释原因 [代码] · Issue #609 · haizlin/fe-interview