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. SqlServer中的自增的ID的最后的值:

    SqlServer中的自增的ID的最后的值: SELECT SCOPE_IDENTITY() --返回插入到同一作用域中的 IDENTITY 列内的最后一个 IDENTITY 值.SELECT @@I ...

  2. MVP 2015社区大讲堂之:在ASP.NET应用中执行后台任务

    昨天下午,在微软的MVP 2015社区大讲堂上给大家分享了一个题目:在ASP.NET应用中执行后台任务.这是一点都不高大上,并且还有点土气的技术分享.不过我相信很多人都遇到过这样的问题. 虽然是一个很 ...

  3. mvc jquery 修改 viewbag

    [HttpGet]        public ActionResult Modify(int id)        {            Books mod=db.Books.Where(b = ...

  4. [javascript] 判断 iframe 是否加载完成

    from http://www.planabc.net/2009/09/22/iframe_onload/ var iframe = document.createElement("ifra ...

  5. 实体类的枚举属性--原来支持枚举类型这么简单,没有EF5.0也可以

    通常,我们都是在业务层和界面层使用枚举类型,这能够为我们编程带来便利,但在数据访问层,不使用枚举类型,因为很多数据库都不支持,比如我们现在用的SqlServer2008就不支持枚举类型的列,用的时候也 ...

  6. Webform(Linq高级查、分页、组合查询)

    一.linq高级查 1.模糊查(包含) 1 public List<User> Select(string name) 2 { 3 return con.User.Where(r => ...

  7. [Android] 建立与使用Library

    [Android] 建立与使用Library 前言 使用Eclipse开发Android项目时,开发人员可以将可重用的程序代码,封装为Library来提供其他开发人员使用.本篇文章介绍如何将可重用的程 ...

  8. C#如何根据配置实现动态窗体

    本文主要讲述如何根据UI配置来动态生成控件, 并添加到窗体上来构建UI窗体,当用户在每个控件上完成输入操作后,程序通过遍历控件并用拼接字符串的方式动态生成Insert SQL语句,进而实现了将UI上的 ...

  9. Elastic Image Slider 带缩略图功能的幻灯片

    今天我们要为您展示如何创建一个简单的弹性幻灯片,带有缩略图预览功能.Elastic Image Slider 这款幻灯片能够自动调整以适应到其父容器,我们可以通过幻灯片使用缩略图预览或幻灯片的自动播放 ...

  10. jQuery立体式数字滚动条增加

    1.html结构 <div class="numberRun1"></div> 2.js <script type="text/javasc ...