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 ...
随机推荐
- ActionSupport与action区别
action是接口,只有一个execute方法需要实现.ActionSupport是action接口的一个实现类.这个类除了实现action接口还实现了Validateable(用于验证)等接口,开发 ...
- mysql: see all open connections to a given database?
SHOW PROCESSLIST or show status where `variable_name` = 'Threads_connected';
- 口袋微博android源码服务端和客户端
刚刚在源码天堂看到了一个不错的安卓SNS应用源码,而且也比较完整的,它基本具备了新浪微博的所有功能,包括查看最新的微博.微博评论.好友资料.回复评论以及发私信等,除此之外,还提供了许多独有的特色功能: ...
- 【转】php中XML、XSLT的结合运用
原文:http://blog.csdn.net/bjbs_270/article/details/140253 下面我要讲的是一个简单的从数据库中抽取数据,生成XML文档,使用XSLT转换成HTM ...
- No.014:Longest Common Prefix
问题: Write a function to find the longest common prefix string amongst an array of strings. 官方难度: Eas ...
- /dev/random 和 /dev/urandom的一点备忘
1. 基本介绍 /dev/random和/dev/urandom是Linux系统中提供的随机伪设备,这两个设备的任务,是提供永不为空的随机字节数据流.很多解密程序与安全应用程序(如SSH Keys, ...
- java8中的map和reduce
java8中的map和reduce 标签: java8函数式mapreduce 2014-06-19 19:14 10330人阅读 评论(4) 收藏 举报 分类: java(47) FP(2) ...
- get传递中文产生乱码的解决方式汇总
1 最基本的乱码问题. 这个乱码问题是最简单的乱码问题.一般新会出现.就是页面编码不一致导致的乱码. <%@ page language="java" pageEncodin ...
- Loadrunner中web_find和web_reg_find函数的使用与区别
总结一下Loadrunner中的检查点函数,主要介绍两个函数:web_find()和web_reg_find():这两个函数均用于内容的查找,但两者也有本质的区别,具体介绍如下:一.web_find( ...
- linux基础知识总结
使用linux将近一年了,一直都没有时间来总结一下,借着最近在整理知识框架的机会总结一下linux的应用知识. 1.linux有两个目录很特殊,一个是~,另一个是/.两个目录的含义不一样,/是系统 ...