第一个问题是我在采访中被问到的,说实话,我看到自己真的很困惑并且展示了门,
考虑一下片段:
案例a:
var sayHello = new Function("alert('Hello there');");
alert(sayHello instanceof Function); // true
alert(sayHello instanceof Object); // true, since every
// object inherits from Object
Run Code Online (Sandbox Code Playgroud)
案例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?
Run Code Online (Sandbox Code Playgroud)
根据我的理解,函数必须在ins的原型链中?
ins <-- myFunction <-- Function <-- Object
Run Code Online (Sandbox Code Playgroud)
Wik*_*hla 10
你似乎new在Javascript中误解了这里.
该
new myFunction()
Run Code Online (Sandbox Code Playgroud)
不会创建该函数的新实例.相反,它创建了一个新对象,它继承myFunction.prototype并调用myFunction,将对象传递this给函数.
因此,您还没有真正创建函数的新实例,您ins不是函数.您可以通过尝试假装它来轻松验证它:
var myFunction = function(){
}
var ins = new myFunction();
ins(); <-- error, ins is not a function
Run Code Online (Sandbox Code Playgroud)
既然它不是一个函数,为什么你会期望Function它在它的原型链?
| 归档时间: |
|
| 查看次数: |
124 次 |
| 最近记录: |