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. 2015暑假多校联合---Mahjong tree(树上DP 、深搜)

    题目链接 http://acm.split.hdu.edu.cn/showproblem.php?pid=5379 Problem Description Little sun is an artis ...

  2. Eclipse保存文件时自动格式化代码

    实现效果:Ctrl+S会自动格式化并保存代码. 应用上图所示效果之后,在每次对Eclipse保存的时候都会实现自动格式化代码. 1. Fomated All lines,格式化该文件的所有代码:还是 ...

  3. Win7 电脑设置临时网络,无法加入网络;internet禁止网络共享

    1.电脑的本地连接中的共享,被管理员禁用.网上试了一些方法,都不可行.最后想到修改注册表.我找到了注册表中的shared选项.将0修改为1.则实现了本地连接的共享. 2.但是即便如此,由本地连接分享出 ...

  4. Scalaz(19)- Monad: \/ - Monad 版本的 Either

    scala标准库提供了一个Either类型,它可以说是Option的升级版.与Option相同,Either也有两种状态:Left和Right,分别对应Option的None和Some,不同的是Lef ...

  5. Vue从零开始(一)

    一.什么是Vue? Vue.js(读音 /vjuː/, 类似于 view) 是一套构建用户界面的 渐进式框架.与其他重量级框架不同的是,Vue 采用自底向上增量开发的设计.Vue 的核心库只关注视图层 ...

  6. 【转】给Windows + Apache 2.2 + PHP 5.3 安装PHP性能测试工具 xhprof

    原文链接:http://blog.snsgou.com/post-816.html 1.下载XHProf 到这里 http://dev.freshsite.pl/php-extensions/xhpr ...

  7. 向 Web 开发人员推荐35款 JavaScript 图形图表库

    图表是数据图形化的表示,通过形象的图表来展示数据,比如条形图,折线图,饼图等等.可视化图表可以帮助开发者更容易理解复杂的数据,提高生产的效率和 Web 应用和项目的可靠性. 在这篇文章中,我们收集了3 ...

  8. 定时器相关 setTimeout setInterval 函数节流

    这个问题也是在参加百度的前端技术学院中遇到的 任务中需要用js实现动画  导师给的评价中setInterval会导致bug 当时不理解   下面把自己学习的过程分享出来 再次理解单线程   老是说js ...

  9. [deviceone开发]-do_SlideListView的简单示例

    一.简介 利用提供的SlideListVIew实现那种cell可以滑动露出底部按钮的功能 主要组件:do_slidelistview 二.效果图 三.相关讨论 http://bbs.deviceone ...

  10. ae_feature的插入、复制和删除

    1.插入 /// <summary> ///向featureclass中批量插入features ,批量插入features,用buffer的方法,要比循环一个个Store的方法快 /// ...