I have been trying to write a constructor function that would make an object chock full of complex methods. These methods process variables of their parents as-well as call on sibling methods. Here’s the best example I can give you. It’s for an improvised web-based console.
function ConsoleCont(type,instace){
this.type=type;
this.input=$('conI');//input type=text
this.output=$('conO');//textarea
this.commandRecall=new Array;
//event listeners for enter-key to this.send(), etc.
this.send=function(){
if(this.input.value){this.commandRecall.push(this.input.value);}
this.consoleConcat("> "+this.input.value);
/*Code to send via AJAX*/
this.input.value="";
}
this.consoleConcat=function(command){
/*code to push to Textarea*/
}
this.receive=function(latestLine){
this.consoleConcat(latestLine)
}
}
Now I find myself needing to type “this.” for everything I reference within the object; is there anyway to have it assume ‘this.’ (like C++’s using namespace or something) or perhaps my methods for this a bit inefficient? I’m not looking for any Jquery solutions, I had predefined $(''); myself, incase you caught that.
You can ditch a few
this‘s in your code, as far as I can see:So, checking your code for the necessity of values or functions being properties can reduce the number of
this‘s. The only other mechanism to reduce typing allthisall over may indeed be usingwith, but that has some pitfalls, as Douglas Crockford explained here.