javascript - 在构造函数的方法中替代 'this.variable'

标签 javascript

我一直在尝试编写一个构造函数,使一个对象充满复杂的方法。这些方法处理它们父类的变量,并调用同级方法。这是我能给你的最好的例子。它适用于基于 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 .

关于javascript - 在构造函数的方法中替代 'this.variable',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7377625/

相关文章:

javascript - 控制台中的缓存对象?

javascript - 有没有不同的方法来删除 jquery 中的类?

javascript - 在 Ember.js 中计算日期差异

javascript - Foundation 6 Abide 不使用 Ajax/Dynamic Html

php - ajax真的有效吗?

java - 你能调用带有链接的 servlet 吗?

javascript - 隐藏和显示不适用于悬停()?

javascript - 如何将带有 script 标签的 div 附加到 li 标签中?

javascript - 需要隐藏具有禁用属性的选项

javascript - 两个同步事件创建一个无限循环