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. java调用Oracle分页存储过程

    Java程序 package com.test; import java.sql.CallableStatement; import java.sql.Connection; import java. ...

  2. 孙鑫MFC学习笔记18:ActiveX

    18 1.容器和服务器程序 2.InvalidateControl重绘控件 3. 4.GetBackColor获取背景色 5.GetForeColor获取前景色 6.TranslateColor进行颜 ...

  3. 【Java每日一题】20161207

    package Dec2016; public class Ques1207 { public static void main(String[] args) { new Test(); new Te ...

  4. C语言文件方式输入与输出(最简洁方便实用的一种方式)

    freopen("inputfile.txt", "r", stdin); freopen("outputfile.txt", " ...

  5. Mysql调试存储过程最简单的方法

    以前同事告诉我用临时表插入变量数据来查看,但是这种方法过于麻烦,而且Mysql没有比较好的调试存储过程的工具.今天google了下发现可以用select + 变量名的方法来调试...真是让我汗颜啊. ...

  6. 解决在android开发中ViewPager中Gallery无法滑动问题

    我的是在viewpager中某个fragment中有gallery... 导致无法滑动,网上找到解决方法. 自定义Gallery. 代码: import android.content.Context ...

  7. HTML标签小结

    HTML:超文本标记语言 超:超链接       超文本:超出文本(可加入图片,文字,音频视频播放器)  标记:标签 HTML文档 以<html...>开始 , 以</html> ...

  8. Scalaz(33)- Free :算式-Monadic Programming

    在任何模式的编程过程中都无法避免副作用的产生.我们可以用F[A]这种类型模拟FP的运算指令:A是可能产生副作用的运算,F[_]是个代数数据类型ADT(Algebraic Data Type),可以实现 ...

  9. Windows 7 性能优化

    1."计算机" 2.右键>"属性" 3."高级系统设置">"高级" 4."性能"> ...

  10. 更新整理本人所有博文中提供的代码与工具(C++,2013.10)

    为了更方便地管理博文中涉及的各种代码与工具资源,现在把这些资源迁移到 Google Code 中,有兴趣者可前往下载. C++ 1.<通用高性能 Windows Socket 组件 HP-Soc ...