Javascript 向方法添加方法
我希望我的代码如下所示:Javascript 向方法添加方法,javascript,Javascript,我希望我的代码如下所示: 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 <--- } } 功能选择(选择器){
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 <---
}
}
功能选择(选择器){
this.where=函数(where){
//用where和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*/}}
}}
}
您可以向每个返回的对象添加其他函数
Jsfiddle:
如果您试图使和和位于同一对象上,请改为:
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 of 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
}
看起来您试图实现的是调用方法链接
,请在此阅读:是的,它很有效!我会检查您的,但我认为有一种不同的方法,像jQuery的,但是谢谢,我很感激!