Created
June 15, 2011 18:36
-
-
Save jimmycuadra/1027779 to your computer and use it in GitHub Desktop.
Examples of call, apply, and bind
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Our implementation of Function.prototype.bind | |
Function.prototype.bind = function() { | |
var __method = this, args = Array.prototype.slice.call(arguments), object = args.shift(); | |
return function() { | |
var local_args = args.concat(Array.prototype.slice.call(arguments)); | |
if (this !== window) local_args.push(this); | |
return __method.apply(object, local_args); | |
} | |
}; | |
// Examples of call, apply, and bind | |
function Module() { | |
this.items = ["one", "two", "three"]; | |
} | |
Module.prototype.print = function () { | |
console.log(this.items.join(" ") + " / " + Array.prototype.join.call(arguments, " ")); | |
}; | |
var m = new Module(); | |
m.print("called", "on", "an", "instance", "of", "Module"); | |
var foo = { items: ["four", "five", "six"]} | |
Module.prototype.print.call(foo, "called", "via", "Function.prototype.call"); | |
Module.prototype.print.apply(foo, ["called", "via", "Function.prototype.apply"]); | |
var boundFunction = Module.prototype.print.bind(foo, "called", "via", "Function.prototype.bind"); | |
boundFunction(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Singleton = function () { | |
var privateInfo = "you can't see this"; | |
return { | |
exposePrivateInfo: function () { | |
console.log(privateInfo); | |
} | |
}; | |
}(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Foo = function () { | |
$(this.setup.bind(this)); | |
$(functionName); | |
$(function () { | |
functionName(); | |
}); | |
} | |
Foo.prototype.bar = function () { | |
console.log("hello"); | |
}; | |
var f = new Foo(); | |
var f2 = new Foo(); | |
f.bar(); | |
f2.bar(); | |
f.bar = function () { | |
console.log("I was changed!"); | |
} | |
f.bar(); | |
var Module = function () { | |
this.name = "Ray"; | |
$(this.setup.bind(this)); | |
}; | |
Module.prototype.setup = function () { | |
$('div').click(this.listenClick.bind(this)); | |
}; | |
Module.prototype.listenClick = function (evt) { | |
var domobject = $(evt.currentTarget); | |
alert(this.name); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment