gpt4 book ai didi

javascript - instanceof 在 JavaScript 中的函数

转载 作者:数据小太阳 更新时间:2023-10-29 05:01:05 25 4
gpt4 key购买 nike

面试的第一个问题,老实说,我看到自己真的很困惑,就把门关了,

考虑片段:

案例一:

    var sayHello = new Function("alert('Hello there');");
alert(sayHello instanceof Function); // true
alert(sayHello instanceof Object); // true, since every
// object inherits from Object

情况 b:

    var myFunction = function(){

}

var ins = new myFunction();
alert(ins instanceof myFunction); // ofcourse, true
alert(myFunction instanceof Function); // true

alert(ins instanceof Function); // false, Why is this not true?

根据我的理解,Function 必须位于 原型(prototype)链 中插入

ins <-- myFunction <-- Function <-- Object

最佳答案

您似乎误解了 Javascript 中的 new

new myFunction()

不会创建函数的新实例。相反,它会创建一个继承自 myFunction.prototype 的新对象并调用 myFunction,将对象作为 this 传递给函数。

因此,您还没有真正创建函数的新实例,您的 ins 不是函数。您可以通过尝试假装它来轻松验证它:

var myFunction = function(){

}

var ins = new myFunction();

ins(); <-- error, ins is not a function

既然它不是一个函数,为什么你会期望 Function 在它的原型(prototype)链中?

关于javascript - instanceof 在 JavaScript 中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32368366/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com