首页 > 调用prototype的方法为什么说方法不存在?

调用prototype的方法为什么说方法不存在?

(function() {
    //use a private class
    function _$(els) {
        this.elements=[];
        //why '++i' ?
        for (var i=0,len=els.length;i<len;++i) {
            var element=els[i];
            if (typeof element ==='string') {
                element=document.getElementById(element);
            }
            this.elements.push(element);
        }
        return this.elements;
    }
    
    //add method to prototype and return this.
    _$.prototype={
        each:function(fn) {
            for (var i=0,len=this.elements.length;i<len;i++) {
                fn.call(this,this.elements[i]);
            }
            return this;
        },
        setStyle:function(prop,value) {
            this.each(function(el) {
                el.style[prop]=value;
            });
            return this;
        },
        show:function(){
            var that = this;
            this.each(function(el) {
                that.setStyle("display","block");
            });
            return this;
        },
        addEvent:function(type,fn) {
            var add=function(el) {
                if (window.addEventListener) {
                    el.addEventListener(type,fn,false);
                }else if (window.attachEvent) {
                    el.attachEvent('on'+type,fn);
                }
            };
            this.each(function(el) {
                add(el);
            });
            return this;
        }
    };
    
    //return window._$
    window.$=function() {
        return new _$(arguments);
    };
})();

//TODO
$("test").addEvent();

function _$(els) {
        this.elements=[];
        //why '++i' ?
        for (var i=0,len=els.length;i<len;++i) {
            var element=els[i];
            if (typeof element ==='string') {
                element=document.getElementById(element);
            }
            this.elements.push(element);
        }
        // return this.elements;
    }
【热门文章】
【热门文章】