Skip to content

Instantly share code, notes, and snippets.

@thfrei
Created May 18, 2016 10:45
Show Gist options
  • Save thfrei/356871dd7eae75893bc5f1a5be8c65d2 to your computer and use it in GitHub Desktop.
Save thfrei/356871dd7eae75893bc5f1a5be8c65d2 to your computer and use it in GitHub Desktop.
// http://stackoverflow.com/questions/12064040/javascript-what-is-the-best-method-when-creating-chainable-functions - Olegas
function test() {
// when test() is called as a regular function
// it's `this` will be `undefined` (in strict mode) or will refer to a global object
// when test() is called with `new` operator
// it's `this` will be an instance of `test` object
if(!(this instanceof test)) {
// create a new object
return new test();
}
else {
// this is a `new object` creation
console.log('new Test created');
}
}
// declare functions which will be accessible on test object
test.prototype.someFunc = function() {
console.log('someFunc');
return this;
};
test.prototype.someFunc2 = function() {
console.log('someFunc2');
return this;
};
// declare a `chaining` function - will create a new `test` object
test.prototype.test = function() {
return new test(); // new instance will be created
};
// With this code you are now able to run the following code
test().someFunc().someFunc2().test().someFunc().someFunc().test().test()
//The following string will be written at the console
//
//new Test created
//someFunc
//someFunc2
//new Test created
//someFunc
//someFunc
//new Test created
//new Test created
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment