Skip to content

Instantly share code, notes, and snippets.

@DmitrySoshnikov
Created August 16, 2011 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DmitrySoshnikov/1149186 to your computer and use it in GitHub Desktop.
Save DmitrySoshnikov/1149186 to your computer and use it in GitHub Desktop.
Features of bound functions
/**
* Features of bound functions.
*
* See: http://dmitrysoshnikov.com/notes/note-1-ecmascript-bound-functions/
*
* by Dmitry Soshnikov <dmitry.soshnikov@gmail.com>
* MIT Style License
*/
var F = function () {};
F.prototype.y = 20;
var that = {x: 10};
var B = F.bind(that);
// no "prototype" property
console.log("B.prototype:", B.prototype); // undefined
// "F.prototype" property of "F" is used
// to set the "__proto__" of "o"
var o = new B;
console.log("o.y:", o.y); // 20, from "F.prototype"
// and exactly "F.prototype" is used
// in "instanceof" test
console.log("o instanceof B:", o instanceof B); // true
console.log("o instanceof F:", o instanceof F); // true
// manual changing of "B.prototype"
// won't help, still "F.prototype" is used
B.prototype = {
constructor: B,
z: 30
};
var q = new B;
console.log("q.z:", q.z); // undefined!, no "B.prototype" is used
console.log("q.y:", q.y); // 20, still from "F.prototype"
// and again
console.log("q instanceof F:", q instanceof F); // true
console.log("q instanceof B:", q instanceof B); // true
console.log("o instanceof F:", o instanceof F); // true
console.log("o instanceof B:", o instanceof B); // true
// But. "Object.create" also sets "__proto__"
var t = Object.create(B.prototype); // use our manual prototype with {... z: 30}
console.log("t.z:", t.z); // 30, huray!, from "B.prototype"
// but...
console.log("t instanceof B:", t instanceof B); // false!, since "F.prototype" is used for test
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment