我一直在尝试编写一个构造函数,该函数会使对象充满复杂的方法。这些方法还处理其父母的变量以及对同级方法的调用。这是我能给你的最好的例子。这是用于基于Web的简易控制台。

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)
    }
}


现在,我发现自己需要输入“ this”。我在对象中引用的所有内容;无论如何,有没有假设它是“这个”。 (例如C ++的using namespace之类的东西)还是我的方法效率低下?我没有在寻找任何Jquery解决方案,我自己已经预定义了$('');,以防万一您抓住了它。

最佳答案

据我所知,您可以在代码中放弃一些this

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)
    }
}


因此,检查代码中值或函数是否为属性的必要性可以减少this的数量。减少全部键入this的唯一其他机制可能确实是使用with,但这有一些陷阱,例如Douglas Crockford explained here

10-05 21:05
查看更多