Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@bengfarrell
Created August 7, 2012 00:49
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 bengfarrell/3280073 to your computer and use it in GitHub Desktop.
Save bengfarrell/3280073 to your computer and use it in GitHub Desktop.
Instance vs Prototype definitions
/**
* don't know how to use prototype style class defs. It's possible to use method.apply to infer scope,
* however it gets complicated when using 3rd party libs and passing a cb function as a parameter.
* I've seen context wrappers that do this, but it seems overly complicated when I can just use instance style
*/
function InstanceStyleTest() {
var self = this;
this.methodA = function() {
// calling direct - both methods work
// this is instance scope, and self is in scope, so self == this
this.success("this");
self.success("self");
}
this.methodB = function() {
setInterval(this.methodC, 1000);
}
this.methodC = function() {
// Doesn't work - our scope is now the Window, so this no longer points to the instance
// this.success();
// Does work - even though we're scoped outside the class, we appear to be in a closure,
// so going up the chain, we find self
self.success("self as callback");
}
this.success = function(from) {
console.log("Success from " + from );
}
}
function PrototypeStyleTest() {
var self = this;
}
PrototypeStyleTest.prototype.methodA = function() {
this.success("this"); // this works since this is in scope
//self.success(); // but this doesn't -- since we don't go up the chain in prototype I assume
//console.log(this); // this correctly points to this instance (I think...or is it to the prototype?)
//console.log(self); // apparently self is window?
}
PrototypeStyleTest.prototype.methodB = function() {
setInterval(this.methodC, 1000);
}
PrototypeStyleTest.prototype.methodC = function() {
// Doesn't work - our scope is now the Window, so this no longer points to the instance
this.success("this as callback");
// Doesn't work either - since self never worked in this design pattern in the first place
self.success("self as callback");
}
PrototypeStyleTest.prototype.success = function(from) {
console.log("Success from " + from );
}
var instStyle = new InstanceStyleTest();
console.log("-- Instance Style --");
instStyle.methodA();
instStyle.methodB();
var protoStyle = new PrototypeStyleTest();
console.log("-- Prototype Style --");
protoStyle.methodA();
protoStyle.methodB();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment