JavaScript Patterns 6.7 Borrowing Methods
Scenario
You want to use just the methods you like, without inheriting all the other methods that you’ll never need. This is possible with the borrowing methods pattern, which benefits from the function methods call() and apply().
// call() example notmyobj.doStuff.call(myobj, param1, p2, p3); // apply() example notmyobj.doStuff.apply(myobj, [param1, p2, p3]);
Example: Borrow from Array
// Example for calling the slice
function f() {
var args = [].slice.call(arguments, 1, 3);
return args;
}
// example
f(1, 2, 3, 4, 5, 6); // returns [2,3]
Borrow and Bind
When borrowing methods either through call()/apply() or through simple assignment, the object that this points to inside of the borrowed method is determined based on the call expression. But sometimes it’s best to have the value of this “locked” or bound to a specific object and predetermined in advance.
var one = {
name: "object",
say: function (greet) {
return greet + ", " + this.name;
}
};
var two = {
name: "another object"
};
var say = one.say;
// passing as a callback
var yetanother = {
name: "Yet another object",
method: function (callback) {
return callback('Hola');
}
};
one.say('hi'); // "hi, object"
one.say.apply(two, ['hello']); // "hello, another object"
say('hoho'); // "hoho, undefined"
yetanother.method(one.say); // "Holla, undefined"
Solution
This bind() function accepts an object o and a method m, binds the two together, and then returns another function. The returned function as access to o and m via a closure. Therefore even after bind() returns, the inner function will have access to o and m, which will always point to the original object and method.
function bind(o, m) {
return function () {
return m.apply(o, [].slice.call(arguments));
};
}
var twosay = bind(two, one.say);
twosay('yo'); // "yo, another object"
Disadvantage
The price you pay for the luxury of having a bind is the additional closure.
Function.prototype.bind()
ECMAScript 5 adds a method bind() to Function.prototype, making it just as easy to use as apply() and call().
var newFunc = obj.someFunc.bind(myobj, 1, 2, 3);
Implement Function.prototype.bind() when your program runs in pre-ES5 environments.
It’s using partial application and concatenating the list of arguments—those passed to bind()(except the first) and those passed when the new function returned by bind() is called later.
var twosay2 = one.say.bind(two);
twosay2('Bonjour'); // "Bonjour, another object"
References:
JavaScript Patterns - by Stoyan Stefanov (O`Reilly)
JavaScript Patterns 6.7 Borrowing Methods的更多相关文章
- JavaScript Patterns 5.3 Private Properties and Methods
All object members are public in JavaScript. var myobj = { myprop : 1, getProp : function() { return ...
- JavaScript Patterns 6.3 Klass
Commonalities • There’s a convention on how to name a method, which is to be considered the construc ...
- JavaScript Patterns 6.2 Expected Outcome When Using Classical Inheritance
// the parent constructor function Parent(name) { this.name = name || 'Adam'; } // adding functional ...
- JavaScript Patterns 5.8 Chaining Pattern
Chaining Pattern - Call methods on an object one after the other without assigning the return values ...
- JavaScript Patterns 5.4 Module Pattern
MYAPP.namespace('MYAPP.utilities.array'); MYAPP.utilities.array = (function () { // dependencies var ...
- JavaScript Patterns 7.1 Singleton
7.1 Singleton The idea of the singleton pattern is to have only one instance of a specific class. Th ...
- JavaScript Patterns 6.6 Mix-ins
Loop through arguments and copy every property of every object passed to the function. And the resul ...
- JavaScript Patterns 6.5 Inheritance by Copying Properties
Shallow copy pattern function extend(parent, child) { var i; child = child || {}; for (i in parent) ...
- JavaScript Patterns 6.4 Prototypal Inheritance
No classes involved; Objects inherit from other objects. Use an empty temporary constructor function ...
随机推荐
- EXCEL countif函数多条件
在MS EXCEL中,countif如果要满足多个条件怎么办呢? 1.答案就是:使用条件集合{}和sum函数. 即在countif()第二个参数中使用条件集合{},然后用sum()函数求满足这些条件的 ...
- 点/边 双连通分量---Tarjan算法
运用Tarjan算法,求解图的点/边双连通分量. 1.点双连通分量[块] 割点可以存在多个块中,每个块包含当前节点u,分量以边的形式输出比较有意义. typedef struct{ //栈结点结构 保 ...
- jquery内容选择器(匹配包含指定选择器的元素)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...
- 蘑菇街2015校招 Java研发笔试题 详解
1. 对进程和线程描述正确的是( ) A. 父进程里的所有线程共享相同的地址空间,父进程的所有子进程共享相同的地址空间. B. 改变进程里面主线程的状态会影响其他线程的行为,改变父进程的状态不会影 ...
- 瞬间读懂什么是互联网思维、大数据、O2O、众筹、红海
1.什么叫大数据? 某必胜客店的电话铃响了,客服人员拿起电话. 客服:必胜客.您好,请问有什么需要我为您服务? 顾客:你好,我想要一份…… 客服:先生,烦请先把您的会员卡号告诉我. 顾客:16846 ...
- GJM:用C#实现网络爬虫(一) [转载]
网络爬虫在信息检索与处理中有很大的作用,是收集网络信息的重要工具. 接下来就介绍一下爬虫的简单实现. 爬虫的工作流程如下 爬虫自指定的URL地址开始下载网络资源,直到该地址和所有子地址的指定资源都下载 ...
- CSS3里的display
默认值:inline 适用于:所有元素 继承性:无 动画性:否 none: 隐藏对象.与visibility属性的hidden值不同,其不为被隐藏的对象保留其物理空间 inline: 指定对象为内联元 ...
- [js开源组件开发]tip提示组件
tip提示组件 常见的应用场景中,总是难免会遇到提示信息,比如显示不完全时需要鼠标移上去显示title,比如验证时的错误提示,比如操作按钮的辅助说明等,所以我独立出来了一个小的js组件,tip提示组件 ...
- 发测试 HTML/FILE/MYSQL/动态 20151120
NilCMS几种页面输出方式: 1.直接生成html.不进行php处理. 2.生成文件缓存.针对于URL中单个目录文件过多,不利于管理.只进行PHP处理,不连接mysql. 3.生成mysql缓存.数 ...
- MyGame--java语言编写的打飞机游戏(附源码下载)
运行效果如下图所示: 点击这里进行下载, 还有源码已经传至我的github上,还有一些小bug,欢迎大家改正. 说明:最后打boss的效果还没做,爆炸的图片也没好,欢迎大家修改.