【问题标题】:call function without parenthesis不带括号的调用函数
【发布时间】:2015-09-10 13:40:35
【问题描述】:

这让我很困惑,我正在尝试创建一个类似 Jquery 的标识符。

$.ajax
$('object')

jquery 标识符$ 可以不带括号调用。

这是我得到的一些代码:

function initialized_object(){
    this.method = function(){
        console.log('this is a string');
    }
}
var o = function (args){
    if(arguments.length > 0){
        //return N$(arguments[0], arguments[1]);
    }else{
        return new initialized_object();
    }
};
o.prototype.constructor.toString = function(){
    this.call(this);
}
o().method();

我想用o.method()代替o().method()

我查看了 jquery 源,试图找到解决方案,但无济于事:http://code.jquery.com/jquery-1.11.3.js


这就是我正在使用的:

(如果您有任何想法)

function N$_no_parameters(){
    this.ajax = function(func){
        func();
    };
};
var N$_np = new N$_no_parameters();

var N$_CURRENT_EVENT_THIS = null;
function N$(selector, within){
    this.co = "hi";
    if (!Array.prototype.indexOf){
        Array.prototype.indexOf = function(elt /*, from*/){
            var len = this.length >>> 0;
            var from = Number(arguments[1]) || 0;
            from = (from < 0) ? Math.ceil(from) : Math.floor(from);
            if (from < 0)
                from += len;
            for (; from < len; from++){
                if (from in this && this[from] === elt)
                    return from;
            }
            return -1;
        };
    }
    var DOM_N$ = function(selector, within, frame){
        this.frame = frame || {
            win: (within != undefined)? within.contentWindow || this.constructor.caller.arguments[0] : this.constructor.caller.arguments[0],
            doc: (within != undefined)? within.contentDocument || this.constructor.caller.arguments[0].document : this.constructor.caller.arguments[0].document,
            this: this.constructor.caller.caller.caller.caller.caller
        };

        if(selector instanceof Object){
            if(selector.defaultView == this.frame.win){//selector is document
                this.selector = selector;
                this.nodes = [this.selector];
            }else if(selector.document == document){//selector is window
                this.selector = selector;
                this.nodes = [this.selector];
            }else if(selector instanceof this.frame.this){// selector is this
                this.selector = N$_CURRENT_EVENT_THIS.selector;
                this.nodes = N$_CURRENT_EVENT_THIS.nodes;//
            }else if(selector instanceof Element){//selector is DOM
                this.selector = selector;
                this.nodes = [this.selector];
            }else{
                this.selector = selector;
                this.nodes = new Array();
                for(var key in selector){
                    var dom_n$_ = N$(selector[key]).nodes;
                    for(var key_ in dom_n$_){
                        if(this.nodes.indexOf(dom_n$_[key_]) == -1){
                            this.nodes.push(dom_n$_[key_]);
                        }
                    }
                }
            }
        }else if(typeof selector == "string"){
            this.selector = selector;
            this.nodes = $prepare(this.selector, this.frame.doc);
        }
        this.event = function(event_, func){
            var that = this;
            actionair(function(node){
                var events = node.events || {};
                if(node.addEventListener){
                    if((event_) in events){
                        node.removeEventListener(event_, events[event_], true);
                        var tmp___ = events[event_];
                        var tmp__ = function(){
                            this.bar = "hello";
                            N$_CURRENT_EVENT_THIS = that;
                            tmp___(node, event_);
                            new func(node, event_);
                            N$_CURRENT_EVENT_THIS = null;
                        };
                        node.addEventListener(event_, tmp__, true);
                        events[event_] = tmp__;
                    }else{
                        var tmp__ = function(){
                            N$_CURRENT_EVENT_THIS = that;
                            new func(node, event_);
                            N$_CURRENT_EVENT_THIS = null;
                        };
                        node.addEventListener(event_, tmp__, true);
                        events[event_] = tmp__;
                    }
                }else if(node.attachEvent){
                    var ie_event = 'on' + event_;
                    if(event_ in events){
                        node.attachEvent(ie_event, function(){
                            N$_CURRENT_EVENT_THIS = that;
                            new func(node, event_);
                            events[event_](node, event_);
                            N$_CURRENT_EVENT_THIS = null;
                        });
                    }else{
                        node.attachEvent(ie_event, function(){
                            N$_CURRENT_EVENT_THIS = that;
                            new func(node, event_);
                            N$_CURRENT_EVENT_THIS = null;
                        });
                    }
                    events[event_] = func;
                }
                node.events = events;

            }, this);
        }

        this.removeEvent = function(event_){
            actionair(function(node, that){
                var events = node.events || {};
                if(node.removeEventListener){
                    if((event_) in events){
                        node.removeEventListener(event_, events[event_], true);
                        events[event_] = null;
                    }
                }else if(node.detachEvent){
                    var ie_event = 'on' + event_;
                    if((event_) in events){
                        node.detachEvent(ie_event, events[event_]);
                        delete events[event_];
                    }
                }
            }, this);
        }
        this.eachNode = function(func){
            actionair(function(node, that){
                N$_CURRENT_EVENT_THIS = N$(node);
                new func(node);
            }, this);
        }
        this.css = function(attr, value){
            N$_CURRENT_EVENT_THIS = this;
            var attribute = "";
            if(attr.indexOf('-') !== -1){
                var split_attr = attr.split('-');
                for (var i = 0; i < split_attr.length; i++) {
                    if(i != 0)
                        attribute += split_attr[i].charAt(0).toUpperCase() + split_attr[i].slice(1);
                    else
                        attribute += split_attr[i].charAt(0).toLowerCase() + split_attr[i].slice(1);
                };
            }else{
                attribute = attr;
            }

            var properties = new Array();


            actionair(function(node, that){
                if(typeof value != 'undefined'){
                    node.style[attribute] = value;
                }
                if (!that.frame.win.getComputedStyle) {//IE
                    that.frame.win.getComputedStyle = function(el, pseudo) {
                        that.el = el;
                        that.getPropertyValue = function(prop) {
                            var re = /(\-([a-z]){1})/g;
                            if (prop == 'float') prop = 'styleFloat';
                            if (re.test(prop)) {
                                prop = prop.replace(re, function () {
                                    return arguments[2].toUpperCase();
                                });
                            }
                            return el.currentStyle[prop] ? el.currentStyle[prop] : null;
                        }
                        return that;
                    }
                }
                properties.push(that.frame.win.getComputedStyle(node, null).getPropertyValue(attr));

            }, this);
            return properties;
        };

        this.text = function(str){
            actionair(function(node, that){
                node.innerHTML = '';
                node.appendChild(that.frame.doc.createTextNode(str));
            }, this);
        };
        this.appendNode = function(tagname, innerHTML){
            actionair(function(node, that){
                var new_node = that.frame.doc.createElement(tagname);
                new_node.innerHTML = innerHTML;
                node.appendChild(new_node);

            }, this);
        };
        this.innerHTML = function(innerHTML){
            actionair(function(node, that){
                node.innerHTML = innerHTML;
            }, this);
        };
        this.removeNode = function(){
            actionair(function(node, that){
                node.parentNode.removeChild(node);
            }, this);
        };
        this.animate = function(func, from, to, speed){

            var that = this;
            actionair(function(node, that){
                (function animate(func, from, to, speed, node){
                    if(from >= to){
                        N$_CURRENT_EVENT_THIS = that;
                        new func(node, to);
                        N$_CURRENT_EVENT_THIS = null;
                    }else{
                        N$_CURRENT_EVENT_THIS = that;
                        new func(node, from);
                        N$_CURRENT_EVENT_THIS = null;
                        setTimeout(
                            function(){
                                animate(func, from+1, to, speed, node);
                            }, speed
                        );
                    }
                })(func, from, to, speed, node);
            }, this);
        }

        function actionair(func, that){
            for (var i = 0; i < that.nodes.length; i++) {
                (function(i_){
                    N$_CURRENT_EVENT_THIS = that;
                    new func(that.nodes[i_], that);
                    N$_CURRENT_EVENT_THIS = null;
                })(i);
            }
        }
        function $prepare(str, doc){
            str = str.replace(/(\s+>\s+)/g,'>');
            str = str.replace(/(\s+)/g,' ');
            var str_ = str;
            var querys = str.split(/[\s\>]+/);
            var querys_des = Array();

            var ascender = new Array();
            for (var i = 0; i < str_.length; i++) {
                if(str_[i] == ">" || str_[i] == " "){
                    var tmp_ = (str_[i] == ">")? 'next_child' : 'ascended';
                    ascender.push( tmp_);
                }
            };
            var recognizes = new Array();
            for (var i = 0; i < querys.length; i++) {
                var asc_child = null;
                asc_child = ascender[i-1];
                var tmp_ = {
                    "selector": querys[i],
                    "i":i
                };
                recognizes[i] = recognize(querys[i], doc);
                if(i != 0){
                    tmp_["asc_child"] = asc_child;
                }else{
                    tmp_["base_selector"] = true;
                }
                querys_des.push(tmp_);
            };
            return $select(querys_des, recognizes, doc);
        }
        function $select(querys_des, recognizes, parent_, doc){
            var parents = parent_ || null;
            for (var i = 0; i < querys_des.length; i++) {
                if('base_selector' in querys_des[i]){
                    parents = recognizes[querys_des[i]['i']];
                }else if('asc_child' in querys_des[i]){
                    var cur_children = recognizes[querys_des[i]['i']];
                    if(querys_des[i]['asc_child'] == 'next_child'){
                        var compatible = compatible_children(parents, cur_children, querys_des[i]['asc_child'], doc);
                        parents = compatible;
                    }else if(querys_des[i]['asc_child'] == 'ascended'){
                        var compatible = compatible_children(parents, cur_children, querys_des[i]['asc_child'], doc);
                        parents = compatible;
                    }
                }
            };

            return parents;
        }

        function compatible_children(parents, children, type, doc){
            var ret = new Array();
            for (var a = 0; a < parents.length; a++) {
                for (var b = 0; b < children.length; b++) {
                    if(type == 'next_child'){
                        if(parents[a] == children[b].parentNode){
                            if(ret.indexOf(children[b]) == -1)
                                ret.push(children[b]);
                        }
                    }else if(type == 'ascended'){
                        if(isin(parents[a], children[b], doc)){
                            if(ret.indexOf(children[b]) == -1)
                                ret.push(children[b]);
                        }
                    }
                }
            }
            return ret;
        }

        function isin(parent, child, doc){
            var child_ = child;
            var ret = new Array();
            while((child_ = child_.parentNode) && child_ != doc.body){
                if(parent == child_){
                    return true;
                }
            }
            return false;
        }

        function recognize(str, doc){
            var identifier = new Array();

            var id_ = false;
            var class_ = false;
            var dom_ = false;
            if(str.indexOf("#") >= 0){
                id_ = true;
                var tmp = str.split("#")[1];
                if(str.indexOf(".") >= 0){
                    identifier['ID'] = tmp.split(".")[0];
                }else{
                    identifier['ID'] = tmp;
                }
            }

            if(str.indexOf(".") >= 0){
                class_ = true;
                var tmp = str.split(".")[1];
                if(str.indexOf("#") >= 0){
                    identifier['CLASS'] = tmp.split("#")[0];
                }else{
                    identifier['CLASS'] = tmp;
                }
            }


            if(id_ && class_){
                if(str.indexOf("#") < str.indexOf(".")){
                    var tmp = str.split("#")[0];
                    if(tmp.length > 0){
                        dom_ = true;
                        identifier['DOM'] = tmp;
                    }
                }else{
                    var tmp = str.split(".")[0];
                    if(tmp.length > 0){
                        dom_ = true;
                        identifier['DOM'] = tmp;
                    }
                }
            }else if(id_){
                var tmp = str.split("#")[0];
                if(tmp.length > 0){
                    dom_ = true;
                    identifier['DOM'] = tmp;
                }
            }else if(class_){
                var tmp = str.split(".")[0];
                if(tmp.length > 0){
                    dom_ = true;
                    identifier['DOM'] = tmp;
                }
            }else{
                if(str.length > 0){
                    dom_ = true;
                    identifier['DOM'] = str;
                }
            }


            var x;
            if(class_){
                if(typeof doc.getElementsByClassName !== 'function') {//Old browsers
                    x = doc.body.getElementsByTagName("*");
                }else{
                    x = doc.getElementsByClassName(identifier['CLASS']);
                }

            }else if(dom_){
                x = doc.getElementsByTagName(identifier['DOM']);
            }else if(id_){
                x = doc.body.getElementsByTagName("*");
                for (var i = 0; i < x.length; i++) {
                    if(x[i].getAttribute("id") != identifier['ID']){
                        delete x[i];
                    }
                };
            }

            var elements = new Array();


            for (var i = 0; i < x.length; i++) {
                if(id_ && class_){
                    if(x[i].getAttribute("id") == identifier["ID"] && x[i].getAttribute("class") == identifier["CLASS"]){
                        if(dom_){
                            if(x[i].tagName.toLowerCase() == identifier['DOM'].toLowerCase()){
                                elements.push(x[i]);
                            }
                        }else{
                            elements.push(x[i]);
                        }
                    }
                }else if(id_){
                    if(x[i].getAttribute("id") == identifier["ID"]){
                        if(dom_){
                            if(x[i].tagName.toLowerCase() == identifier['DOM'].toLowerCase()){
                                elements.push(x[i]);
                            }
                        }else{
                            elements.push(x[i]);
                        }
                    }
                }else if(class_){
                    if(x[i].getAttribute("class") == identifier["CLASS"]){
                        if(dom_){
                            if(x[i].tagName.toLowerCase() == identifier['DOM'].toLowerCase()){
                                elements.push(x[i]);
                            }
                        }else{
                            elements.push(x[i]);
                        }
                    }
                }else{
                    if(dom_){
                        if(x[i].tagName.toLowerCase() == identifier['DOM'].toLowerCase()){
                            elements.push(x[i]);
                        }
                    }else{
                        elements.push(x[i]);
                    }
                }

            };

            return elements;
        }
    };

    var selectors = new Array();
    console.log('arguments' + arguments.length);
    if(arguments.length > 0){
        return new (function(selector, within){
            if(typeof within == typeof {}){
                if(within.nodes != undefined){
                    var ret = new Array();
                    for (var i = within.nodes.length - 1; i >= 0; i--) {
                        ret.push(do_node_select(selector, within.nodes[i]));
                    };
                    return ret;
                }else if(
                    typeof Node === "object" ? within instanceof Node : 
                    within && typeof within === "object" && typeof within.nodeType === "number" && typeof within.nodeName==="string"
                ){
                    return do_node_select(selector, within);
                }
            }
            return do_node_select(selector, undefined);

            function do_node_select(selector, node){


                    var N$_new = new ( function(win, doc){
                        return new DOM_N$(selector, node || undefined);
                    })(window);

                    var N$_ = null;
                    if(selectors.length > 0){
                        for (var i = selectors.length - 1; i >= 0; i--) {
                            if(selectors[i].selector == selector){
                                var not_in = new Array();
                                for (var b = N$_new.nodes.length - 1; b >= 0; b--) {
                                    if(selectors[i].nodes.indexOf(N$_new.nodes[b]) == -1){
                                        not_in.push(N$_new.nodes[b]);
                                    }
                                };
                                for (var a = not_in.length - 1; a >= 0; a--) {
                                    if(selectors[i].nodes.indexOf(not_in[a]) == -1){
                                        selectors[i].nodes.push(not_in[a]);
                                    }
                                };
                                N$_ = selectors[i];
                                break;
                            }else{
                                N$_ = N$_new;
                            }
                        };
                    }else{
                        N$_ = N$_new;
                        if(N$_.nodes.length > 0){
                            selectors.push(N$_);
                        }
                    }
                    return N$_;

            }
        })(selector, within || undefined);
    }else{
        return N$_np;
    }

};


N$(window).event('load', function(){

    N$.ajax(function(){ // this will not work but using N$().ajax will
        console.log('aaa');
    });
});

这是一个类似于 Jquery 的库,它选择节点并处理事件等等。我想在没有括号的情况下调用我的 ajax 函数的原因是为了清楚起见。

【问题讨论】:

  • 如果你这样做var o = new initialized_object();会发生什么?那么它有效吗?
  • 您还想如何使用o ?顺便说一句,你的toString方法真的很奇怪,不知道做o.prototype.constructor.toString的价值是什么
  • o.prototype.constructor.toString 在调用 object.toString 时调用对象,因此基本上只使用 o 就会调用对象。但这不起作用。
  • @musefan 是的,可以,但是 o 可以返回 2 个不同的对象,除非我有 2 个不适合我的不同标识。但我正在考虑。
  • 我将发布我正在使用的代码,也许有人可以提供一些提示。

标签: javascript jquery


【解决方案1】:

jquery 标识符 $ 可以不带括号调用。

没有。该函数没有被调用。

函数是对象。对象可以具有属性。这只是访问函数对象的属性。

function foo() {
  return 1;
}

foo.bar = 2;

alert(foo.bar);
alert(foo());

我想使用 o.method() 而不是 o().method()

这些陈述的含义不同。

第一个调用方法method的值是调用o函数时返回的

第二个调用o函数的method方法本身。

第二个根本不接触初始化的对象(甚至创建一个)。

【讨论】:

  • 这是我在发布此问题之前提出的解决方案之一,我希望避免使用。不过这种方法确实有效,所以我对此表示赞赏。
  • @Richard: 这是 the 的方式,也正是 jQuery 的方式(除了他们使用 jQuery.extend() 辅助方法来设置大部分属性, 但这是 .extend() 方法在内部执行的操作)。
  • @Richard 不信请通读jQueryUnderscore等的源码,都是用这个方法搞定的。
【解决方案2】:

$ 是一个函数。但是 JavaScript 中的函数也是对象,而对象又可以有函数。

也许这种模式更接近您正在寻找的:

var o = {
    method: function() {
    }
};
o.method();

【讨论】:

  • $也是一个函数
  • 谢谢@JuanMendes 我更新了我的答案,以便更清楚地了解您的评论
【解决方案3】:

每次您调用 o() 时,您都会得到一个新实例,该实例的行为会因您的调用方式而异。

如果你只是打电话给o.method,它怎么知道使用哪个引用?像 jQuery 一样,你会这样做

o = o() // or o('something')

这将创建一个全局单例o,然后您可以调用o.method

【讨论】:

  • 但是如何使用变量 o 和带参数的对象 o?
  • @RichardGrant 不知道你在问什么
【解决方案4】:

昆汀的回答是完全正确的。你只是在访问一个财产,没什么大不了的。我只是想补充一点,如果你使用getters,有一种方法可以“调用不带括号的函数”:

window.__defineGetter__("$", function() { 
    //This gets executed when you access $
    console.log('oh hai'); 
    return { foo: 'bar' } 
});

根本不应该这样做,但这是实现问题标题中的内容的一种方式

【讨论】:

    猜你喜欢
    • 2016-06-27
    • 1970-01-01
    • 1970-01-01
    • 2014-03-01
    • 2017-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多