MyQuery错误地将数组标识为实例

时间:2014-11-19 01:04:23

标签: javascript jquery

我正在尝试为库使用类似jQuery的模式,并以this blog post为基础开始......

var myQuery, $$;

(function() {

    myQuery = $$ = function(selector) {
        return new MyQuery(selector);
    };

    var MyQuery = function(selector) {
        // Lets make a really simplistic selector implementation for demo purposes
        var nodes = document.getElementsByTagName(selector);
        for (var i = 0; i < nodes.length; i++) {
            this[i] = nodes[i];
        }
        this.length = nodes.length;
        return this;
    };

    // Expose the prototype object via myQuery.fn so methods can be added later
    myQuery.fn = MyQuery.prototype = {
        // API Methods
        hide: function() {
            for (var i = 0; i < this.length; i++) {
                this[i].style.display = 'none';
            }
            return this;
        },
        remove: function() {
            for (var i = 0; i < this.length; i++) {
                this[i].parentNode.removeChild(this[i]);
            }
            return this;
        }
        // More methods here, each using 'return this', to enable chaining
    };

}());

我遇到了原型链的细节问题。

jQuery(v2.1.1)按预期工作,正确识别实例,而不是数组instanceof它的构造函数...

var jq = $();
// undefined
jq instanceof $.fn.constructor
// true
[] instanceof $.fn.constructor
// false

MyQuery识别实例,但也错误地将数组识别为构造函数的实例......

var mq = $$();
// undefined
mq instanceof $$.fn.constructor
// true
[] instanceof $$.fn.constructor
//true

MyQuery缺少什么才能正确识别实例,没有误报?

1 个答案:

答案 0 :(得分:1)

您没有特别将$$.fn.constructor设置为任何内容,因此它是通用的Object构造函数。

[]Object的实例,所以:

[] instanceof $$.fn.constructor` 

基本上与:

相同
[] instanceof Object

按预期报告true


如果您将此行添加到IIFE的末尾:

myQuery.fn.constructor = MyQuery;
然后,您将获得与JQuery相同的结果。

工作演示:http://jsfiddle.net/jfriend00/n1of58n4/