向方法添加方法

Adding method to a method

本文关键字:方法 添加      更新时间:2023-09-26

我希望我的代码是这样的:

select("*").where("you='me'").and("me='him'").and("game='nes'");

我只有这个:

function select(selector){
    this.where = function(where){
        //Do something with where and select.
        //Add the method AND <---
    }
}

我不知道如何在方法中添加方法添加在哪里。

这有时被称为"流畅接口"

只需从每个功能return this即可。

如果要捕获"选择"上下文,请在该范围内的变量中捕获this,然后在需要时返回它。这很重要,因为this指向当前正在执行的函数。

function select(s){
    var that = this;
    this.where = function(condition){
        that.filter(condition);
        return that; //this == select.where
    }
    this.and = function (condition) {
        that.filter(condition);
        return that;
    }
    this.end = function(){
        return that.results(); // or similar depending on the consumed api of course
    }
    return this; // this == select
}

在每个函数中,将"return this;"放在底部。所以当你调用.and()时,它被调用"this",即"select"。对不起在iPhone上,所以没有格式化!

一种方法:

function select(selector){
    return {where:function(where){
        //do whatever you're doing with where and selector
        return {and:function(whatever){/*do something with whatever*/}}
    }}
}

您可以向每个返回的对象添加其他函数

杰斯菲德尔:http://jsfiddle.net/markasoftware/78aSa/1/

如果您尝试使andwhere位于同一对象上,请改为执行以下操作:

function select(selector){
    var selectObj=this;
    this.where=function(where){
        //do whatever with where and select
        //now add the and method
        selectObj.and=function(whatever){
            //do stuff with selector, where, and whatever
        }
        return selectObj
    }
    return selectObj;
}

这个的jsfiddle:http://jsfiddle.net/markasoftware/34BYa/