先看看一道题:

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

 

解这道题:

new f() //推出:new f() => f

对函数使用new操作符,解释器会做以下几件事:

  1. 创建一个空对象,并将新对象绑定到this关键字。
  2. 执行函数体内的语句。
  3. 如果有return语句且返回值不是原始类型的数据,返回return语句的内容,否则返回this。

本题中的new f()操作只执行到了第二步就已经返回了。所以new f() => f。

接下来的问题是:

f instanceof f //  ??? true or false

 An interesting feature of instanceof is that it not only checks the constructor used to create the object but also checks the prototype chain. The prototype chain contains information about the inheritance pattern used to define the object. For instance, every objectinheritsfromObjectbydefault,soeveryobjectreturnstrueforvalue instanceof Object.  

上面是乌龟书《Maintainable JavaScript》对instanceof的解释。

 posted on 2011-06-25 20:51  一个有双下巴的死胖子  阅读(284)  评论(2编辑  收藏  举报