This is a possible solution
function Something(){
this.$container = "<div></div>";
//this creates a new object in the prototype chain for every instance
this.build = Object.create(this.build);
for (var prop in this.build) {
if (this.build.hasOwnProperty(prop) && typeof this.build[prop] === "function") {
this.build[prop] = this.build[prop].bind(this);
}
}
return this;
}
Something.prototype.build = {
list: function(){
console.log(this.$container);
}
}
Basically you'll bind every function in your this.build
object to a function bound to this
. You could extract this in a utility function and then bind all nested object you need to this. I suppose it must be possible too by manipulating/build the prototype chain but I haven't found it.
I know most of you recommend refactoring, but I thought to put this out there just so you have a complete set of solutions.
Edit
As pointed out, you need to move the build
interface to your constructor in order to have this
bound correctly. This solution is just a way to do this without having to move your code.
solution without using Object.create
This one is cleaner and more explicitly states what it does without messing with prototypes.
function Something(){
this.$container = "<div></div>";
var build = this.build;
this.build = {};
for (var prop in build) {
if (build.hasOwnProperty(prop) && typeof build[prop] === "function") {
this.build[prop] = build[prop].bind(this);
}
}
return this;
}
Something.prototype.build = {
list: function(){
console.log(this.$container);
}
}