Skip to content

Instantly share code, notes, and snippets.

@maxleiko
Created August 4, 2016 08:12
Show Gist options
  • Save maxleiko/efda18c78cc6c9fba9285cea1c5766cd to your computer and use it in GitHub Desktop.
Save maxleiko/efda18c78cc6c9fba9285cea1c5766cd to your computer and use it in GitHub Desktop.
function MyType() {
// this is the constructor: init shit here
this.foo = 'bar';
this.id = 42;
}
// define MyType prototype (available methods for each instances with this bound to proper context)
MyType.prototype = {
init: function init() {
console.log('init');
console.log('foo', this.foo);
console.log('id', this.id);
},
doAsyncWork: function (callback) {
// faking async work with setTimeout()
var self = this;
setTimeout(function () {
// here you cannot access your instance properties with "this"
// because it is bound to the new anonymous function you just created
console.log('logging', self.foo);
}, 1000);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment