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的更多相关文章

  1. JavaScript Patterns 5.3 Private Properties and Methods

    All object members are public in JavaScript. var myobj = { myprop : 1, getProp : function() { return ...

  2. JavaScript Patterns 6.3 Klass

    Commonalities • There’s a convention on how to name a method, which is to be considered the construc ...

  3. JavaScript Patterns 6.2 Expected Outcome When Using Classical Inheritance

    // the parent constructor function Parent(name) { this.name = name || 'Adam'; } // adding functional ...

  4. JavaScript Patterns 5.8 Chaining Pattern

    Chaining Pattern - Call methods on an object one after the other without assigning the return values ...

  5. JavaScript Patterns 5.4 Module Pattern

    MYAPP.namespace('MYAPP.utilities.array'); MYAPP.utilities.array = (function () { // dependencies var ...

  6. 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 ...

  7. JavaScript Patterns 6.6 Mix-ins

    Loop through arguments and copy every property of every object passed to the function. And the resul ...

  8. JavaScript Patterns 6.5 Inheritance by Copying Properties

    Shallow copy pattern function extend(parent, child) { var i; child = child || {}; for (i in parent) ...

  9. JavaScript Patterns 6.4 Prototypal Inheritance

    No classes involved; Objects inherit from other objects. Use an empty temporary constructor function ...

随机推荐

  1. Oracle sqlplus设置显示格式命令详解

    / 运行 SQL 缓冲区 ? [关键词] 对关键词提供 SQL 帮助 @[@] [文件名] [参数列表] 通过指定的参数,运行指定的命令文件 ACC[EPT] 变量 [DEF[AULT] 值] [PR ...

  2. 【Java每日一题】20161128

    package Nov2016; import java.util.ArrayList; import java.util.List; public class Ques1128 { public s ...

  3. 回文字算法(java版本)

    package com.gdh.backtext;import java.util.HashMap;import java.util.Map;import java.util.Map.Entry; p ...

  4. nodejs操作mongodb数据库封装DB类

    这个DB类也算是我经历了3个实际项目应用的,现分享出来,有需要的请借鉴批评. 上面的注释都挺详细的,我使用到了nodejs的插件mongoose,用mongoose操作mongodb其实蛮方便的. 关 ...

  5. HR人力资源战略流程制定

    HR人力资源战略 是指根据企业总体战略的要求,为适应企业生存和发展的需要,对企业人力资源进行开发,提高职工队伍的整体素质,从中发现和培养出一大批优秀人才,所进行的长远性的人力资源管理方面的专业谋划和方 ...

  6. Fiddler (五) Mac下使用Fiddler

      Fiddler是用C#开发的.  所以Fiddler不能在Mac系统中运行.  没办法直接用Fiddler来截获MAC系统中的HTTP/HTTPS,    Mac 用户怎么办呢? Fiddler可 ...

  7. linux 查找目录或文件详解

    查找目录:find /(查找范围) -name '查找关键字' -type d查找文件:find /(查找范围) -name 查找关键字 -print 如果需要更进一步的了解,可以参看Linux的命令 ...

  8. 完整的定时任务解决方案Spring集成+定时任务本身管理+DB持久化+集群

    完整的定时任务解决方案Spring集成+定时任务本身管理+DB持久化+集群 maven依赖 <dependency> <groupId>org.quartz-scheduler ...

  9. phonegap安卓手机开发入门

    先安装安卓开发安环境 http://www.cnblogs.com/zhangsanshi/p/3582368.html 安装phonegap 在安装ant http://www.cnblogs.co ...

  10. HTML5 模拟现实物理效果,感受 Web 技术魅力

    Ball Pool 是一个基于 HTML5 技术的实验,模拟现实物理效果,让你在 Web 中感受自然物体的运动.玩法介绍:可以随意拖动圆球.点击页面背景.晃动浏览器.双击页面背景或者按住鼠标左键,有不 ...