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 ...
随机推荐
- SQL Pretty Printer-不错的SQL格式化工具
前言 好长时间没有写过博客了,人变懒了很多,应该说本来也不怎么勤快.但今天为了这个工具,必须得勤快一下了,天下真的没有免费的午餐. 之前使用过sql server 2000的查询设计器和Toad fo ...
- Get,Post请求中文乱码问题有效解决方法
本文主要介绍如何有效解决web请求中的乱码问题,其实解决方法有很多种,不同的请求类型解决方法也不相同. 本文只介绍最方便的一种: 1.先修改jsp中的编码方式 2.针对Post方式提交的请求如果出现乱 ...
- log4j配置文件详解
在开发中经常会碰到日志,网上关于日志的框架也很多,像log4j.self4j.common-logging等,下面对log4j进行介绍. log4j是java开发的日志框架,具有低侵入的特点,其重点使 ...
- 高效 Java Web 开发框架 JessMA v3.2.3 正式发布
JessMA(原名:Portal-Basic)是一套功能完备的高性能 Full-Stack Web 应用开发框架,内置可扩展的 MVC Web 基础架构和 DAO 数据库访问组件(内部已提供了 Hib ...
- mesos 学习笔记1 -- mesos安装和配置
参考资料: 官方文档:http://mesos.apache.org/documentation 中文翻译:http://mesos.mydoc.io/ GitHub:https://github.c ...
- 多平台下Modbus通信协议库的设计(一)
1.背景 1.1.范围 MODBUS 是 OSI 模型第 7 层上的应用层报文传输协议, 它在连接至不同类型总线或网络的设备之间提供客户机/服务器通信. 自从 1979 年出现工业串行链路的事实标准以 ...
- 记一次CSR上线及总结
终于到上线的时候了,可以好好休息了.放松了,但在没有经过用户确认之前,一切皆有可能发生...... 经历: 项目终于完成,上线文档已准备就绪,等待上线时刻. 在上线之前,忘记了解目前环境的部署架构,注 ...
- ASP.NET登录控件login。
1.Login控件.通常情况下会出现3个核心元素.用户名文本框.密码输入框.提交凭证的按钮. 1>.比较重要的属性:CreateUserText属性:包含站点注册页的链接文本.CreateUse ...
- 12款免费的响应式 WordPress 主题下载
响应式和现代设计风格的多用途 WordPress 主题能够非常灵活的适应所有设备.而高级主题能够更轻松定制,您可以从主题选项中禁用/启用响应模式.多用途的响应式设计的主题是最适合杂志网站,博客网站,想 ...
- javascript中关于数组的一些鄙视题
一.判断一个数组中是否有相同的元素 /* * 判断数组中是否有相同的元素的代码 */ // 方案一 function isRepeat1(arrs) { if(arrs.length > 0) ...