导航栏: 首页 评论列表

Function, Object 互为对方的实例

默认分类 2014/05/12 18:37

http://www.cnblogs.com/burst/archive/2011/11/26/2264466.html

之前曾经学习过 jQuery() instanceof jQuery 的神奇问题,jQuery 通过让 jQuery() 返回与 jQuery 的 prototype 相同的类型的一个实例:

var jQuery = function(select, context) {
  var _jQuery = function(select, context) {
    return new jQuery.fn.init(select, context);
  }
  jQuery.fn = jQuery.prototype = {
    init: function(select, context) {
      ...
    }
  };
  jQuery.fn.init.prototype = jQuery.prototype;
  return _jQuery(select, context);
}
alert(jQuery() instanceof jQuery); //true

搞出了这种神奇的效果。

今天又学习了一下 Function 与 Object 这两个对象的继承关系。

alert(Function instanceof Object);
alert(Object instanceof Function);

结果惊奇地发现 Function instanceof Object 和 Object instanceof Function 都返回 true。

于是 google 之:

因为 Object.prototype 默认是所有对象父类型,因此 Object 类型是 Function 类型 的父类型,而在 javascript 中,所有类型都应该是个 Function,因此 Object 也是 Function 的子类型,从而造成了这种你是我的父类,我也是你的父类的现象。

这种关系与 prototype 无关,因为 Object 是原型链的顶端对象,Object.\_\_proto\_\_ 是 null 或者 function Empty(),而 Function.\_\_proto__ 也同样是 null 或者 function Empty()。

typeof Object "function" Object instanceof Object true Function instanceof Function true Function instanceof Object true

JS中一切皆对象,一切对象(包括简单对象和函数)都是Object的实例


>> 留言评论