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 so开发者_StackOverflow社区mething) 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:
function ConsoleCont(type,instace) {
// ^did you mean instance?
// both input/output are assigned to a fixed value, so they seem
// not specific to an instance, hence can be ('static'-like) variables
var input = $('conI'),
output = $('conO');
// these are really local (instance) properties
this.type = type;
this.commandRecall = [];
// the event listener(s) can be added to the constructors prototype
if (!ConsoleCont.prototype.send){
var proto = ConsoleCont.prototype;
proto.send = function(){
if(input.value){
this.commandRecall.push(this.input.value);
}
consoleConcat("> "+this.input.value);
/*Code to send via AJAX*/
this.input.value = "";
};
}
// if not used as public methods, these methods can be
// assigned and used within the current scope ('private')
function consoleConcat(command){
/*code to push to Textarea*/
}
function receive(latestLine){
consoleConcat(latestLine)
}
}
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 all this
all over may indeed be using with
, but that has some pitfalls, as Douglas Crockford explained here.
Maybe the word with
will help you:
function ConsoleCont(type,instace)
{
with(this)
{
type=type;
input = $('conI');
/* ... */
}
}
Here is an example: http://jsfiddle.net/34trZ/2/
To bring it to the point: it is not possible to avoid typing this
when refering to object properties in the constructor function for this object. Of course, local variables and functions are not qualified with this.
.
精彩评论