robertsosinski / tutorial-scope-in-javascript

Code to accompany my "Binding Scope in JavaScript" tutorial

This URL has Read+Write access

tutorial-scope-in-javascript / example-6.js
100644 23 lines (17 sloc) 0.374 kb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// example-6.js
 
Function.prototype.bind = function(scope) {
  var _function = this;
  
  return function() {
    return _function.apply(scope, arguments);
  }
}
 
alice = {
  name: "alice"
}
 
eve = {
  talk: function(greeting) {
    console.log(greeting + ", my name is " + this.name);
  }.bind(alice) // <- bound to "alice"
}
 
eve.talk("hello");
 
// hello, my name is alice