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 ...
随机推荐
- C#的变迁史 - C# 4.0 之多线程篇
在.NET 4.0中,并行计算与多线程得到了一定程度的加强,这主要体现在并行对象Parallel,多线程Task,与PLinq.这里对这些相关的特性一起总结一下. 使用Thread方式的线程无疑是比较 ...
- MVC之前的那点事儿系列(4):Http Pipeline详细分析(上)
文章内容 继续上一章节的内容,通过HttpApplicationFactory的GetApplicationInstance静态方法获取实例,然后执行该实例的BeginProcessRequest方法 ...
- 背水一战 Windows 10 (9) - 资源: 资源限定符概述, 资源限定符示例
[源码下载] 背水一战 Windows 10 (9) - 资源: 资源限定符概述, 资源限定符示例 作者:webabcd 介绍背水一战 Windows 10 之 资源 资源限定符概述 资源限定符示例 ...
- 孙鑫MFC学习笔记20:Hook编程
1.HOOK拦截消息,设置越后的钩子优先级越高(钩子队列)2.SetWindowHookEx设置钩子 如果thread identifier为0或其他进程创建的线程,回调函数需要在动态链接库中声 ...
- 2016暑假多校联合---Counting Intersections
原题链接 Problem Description Given some segments which are paralleled to the coordinate axis. You need t ...
- jquery常见知识点 总结
1. jquery特点 2. jquery中css选择器用法 jQuery使用了一套css选择器,共有5种,即标签选择器,ID选择器,类选择器,通用选择器和群组选择器,现分述如下: 标签选择器 用 ...
- 转载java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.spinner/com.example.spinner.MainActivity}: java.lang.NullPointerException
今天学习Android开发突然遇到了这个问题,查阅了很多资料,并且对集中原因进行了分析. 错误信息字符串:java.lang.RuntimeException: Unable to start act ...
- windows下打包react-native应用程序
P.S.0:不截图了,上传图片太麻烦,每次只能上传一张.... 先生成签名文件,如果已有签名文件略过此步: keytool -genkey -v -keystore my-release-key.ke ...
- Django messages框架
一.简介 在网页应用中,你经常需要在处理完表单或其它类型的用户输入后,显示一个通知消息(也叫做“flash message”)给用户 对于这个功能,Django 提供基于Cookie 和会话的消息,无 ...
- AH00098 pid file overwritten
错误日志: 由于定义了: <IfModule mpm_winnt_module> ThreadsPerChild 450 MaxConnectionsPerChild 4000 Accep ...