In the first Chain this is bound to the window
and therefore second is not visible (undefined in that scope).
(function(){
var first = function(){
console.log("1st Chain");
console.log(this);
return this;
};
window.second = function(){
console.log("2nd Chain");
}
first().second();
})();
To get rid of an export to the global window object of the second function, you could use a Object that's only visible in the Scope of the anonymous function.
(function(){
var Chain = {};
Chain.first = function(){
console.log("1st Chain");
console.log(this);
return this;
};
Chain.second = function(){
console.log("2nd Chain");
return this;
}
// example
Chain.first().second().first();
// example export
// window.Chain = Chain;
})();
If you want to chain in another scope, you could export your Chain to the window and use it without new, ie. Chain.first().second();.
You could also save a pointer to this (as pointed out by Jonathon):
(function(){
var self = this;
this.first = function(){
console.log("1st Chain");
console.log(this);
return self;
};
this.second = function(){
console.log("2nd Chain");
return self;
}
// example
first().second().first();
// export example
// window.Chain = self;
})();
// exported anonymous function to Chain
// Chain.first().second();
Saving a pointer to this is sometimes necessary, because the this keyword is scope-changing and refers to the context of the executed function.
this does not refer to the instance of the object, where this is used, like you would expect in Java.
Every function can therefore bound to another scope.
To adjust the function context use bind, apply and call.
thisin the first function.thisis about in javascript.