1+ <!doctype html>
2+ < html lang ="en ">
3+ < head >
4+ < title > JavaScript Patterns</ title >
5+ < meta charset ="utf-8 ">
6+ </ head >
7+ < body >
8+ < script >
9+ /* Title: Borrowing Methods
10+ Description: generally a pattern that should be avoided unless one is more comfortable with class than prototype
11+ */
12+
13+ function f ( ) {
14+ var args = [ ] . slice . call ( arguments , 1 , 3 ) ;
15+ return args ;
16+ }
17+
18+ var one = {
19+ name : 'object' ,
20+ say : function ( greet ) {
21+ return greet + ', ' + this . name ;
22+ }
23+ } ;
24+
25+ // test
26+ console . log ( one . say ( 'hi' ) ) ; // "hi, object"
27+
28+ var two = {
29+ name : 'another object'
30+ } ;
31+
32+ console . log ( one . say . apply ( two , [ 'hello' ] ) ) ; // "hello, another object"
33+
34+ // assigning to a variable
35+ // `this` will point to the global object
36+ var say = one . say ;
37+ console . log ( say ( 'hoho' ) ) ; // "hoho, undefined"
38+
39+ // passing as a callback
40+ var yetanother = {
41+ name : "Yet another object" ,
42+ method : function ( callback ) {
43+ return callback ( 'Hola' ) ;
44+ }
45+ } ;
46+ console . log ( yetanother . method ( one . say ) ) ; // "Holla, undefined"
47+
48+ function bind ( o , m ) {
49+ return function ( ) {
50+ return m . apply ( o , [ ] . slice . call ( arguments ) ) ;
51+ } ;
52+ }
53+
54+ var twosay = bind ( two , one . say ) ;
55+ console . log ( twosay ( 'yo' ) ) ; // "yo, another object"
56+
57+
58+ if ( typeof Function . prototype . bind === 'undefined' ) {
59+ Function . prototype . bind = function ( thisArg ) {
60+ var fn = this ,
61+ slice = Array . prototype . slice ,
62+ args = slice . call ( arguments , 1 ) ;
63+ return function ( ) {
64+ return fn . apply ( thisArg , args . concat ( slice . call ( arguments ) ) ) ;
65+ } ;
66+ } ;
67+ }
68+
69+ var twosay2 = one . say . bind ( two ) ;
70+ console . log ( twosay2 ( 'Bonjour' ) ) ; // "Bonjour, another object"
71+
72+ var twosay3 = one . say . bind ( two , 'Enchanté' ) ;
73+ console . log ( twosay3 ( ) ) ; // "Enchanté, another object"
74+ </ script >
75+ </ body >
76+ </ html >
0 commit comments