If you want to chain, just return this
!
var users = function(url){
this.users = []
console.time("api");
d3.json(url, function(data){
console.timeEnd("api");
this.users = data.data
})
return this;
};
users.prototype.somethingElse = function(){
console.log(this.users);
return this;
};
var liveUsers = new users(apiPoint).somethingElse();
The use of return this
keeps the chain going, and you can add additional functions to the class by adding prototype
methods. The this
is retained by using that prototype
capability, however if you wanted to use another function that isn't associated with the class and still use that same this
, then you'd need to get a little trickier:
var users = function(url){
this.users = []
console.time("api");
d3.json(url, function(data){
console.timeEnd("api");
this.users = data.data
})
return this;
},
somethingElse = function(){
console.log(this.users);
return this;
};
var liveUsers = new users(apiPoint);
// bunch of other codey stuffs
somethingElse.call(liveUsers);
By using .call()
applying liveUsers
as the first argument, it overrides whatever this
the somethingElse
function originally had, and gives it the context that you want (making this
=== liveUsers
).
Hope this helps!