向方法添加方法
Adding method to a method
我希望我的代码是这样的:
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/
如果您尝试使and
和where
位于同一对象上,请改为执行以下操作:
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/
相关文章:
- 如何在Angular单元测试中从另一个控制器的rootScope将方法添加到rootScope中
- 如何将onChange方法添加到ExtJS 4表单中的所有字段(textField)中
- 如何向.apply()方法添加回调
- 向 Firebase “push” 方法添加时间戳
- jQuery方法添加一个TextBox
- 如何将方法添加到Html5画布
- 什么'在javascript中将新方法添加到对象中的区别是什么
- 如何在角度控制器中为该方法添加验证
- 是否可以将方法添加到空值的原型中
- 如何使用 util 将方法添加到模块 express() 中
- 在 JavaScript 中隐式地将方法添加到构造函数的原型中
- 如何将另一个方法添加到Pinterest按钮的onlick事件中
- 将方法添加到数字引发异常
- 向方法添加方法
- 通过下拉列表框上的 appendChild 方法添加的项目不会显示在 IE8 下
- 如何将实例方法添加到帆中的所有模型.js
- 为什么我的javascript .push方法添加了太多对象
- 分机.js确认方法添加新行字符
- 使用原型将新方法添加到JScrollPane
- 我想克隆一个 javascript 类. 将方法添加到克隆的属性中,而不实际覆盖现有方法