代码之家  ›  专栏  ›  技术社区  ›  tcooc

从成员方法内访问javascript对象引用

  •  1
  • tcooc  · 技术社区  · 14 年前

    好的,我想知道是否可以将对象的引用转移到函数。如果你不明白我想说什么,这可能有帮助:

    //so i declare the variable `Editor`
    var Editor = new (function(e, d){
        this.edit = e;
        this.dyna = d;
        this.old = ""; //and set these variables inside the object
    
        this.update = function() {
            var ta = $(Editor.edit)[0].value, dy = $(Editor.dyna)[0].contentDocument;
            //what i want is to be able to refer to the variables (ie. "edit") without using "Editor."
            if (Editor.old !== ta) {
                $(dy).text(ta);
                Editor.old = ta;
            }
            window.setTimeout(Editor.update, 150);
        }
    
        return this;
    })("editor","dynamic");
    

    因此,对于更新功能,我希望能够做一些类似的事情:

    this.update = function() {
        var ta = $(edit)[0].value, dy = $(dyna)[0].contentDocument;
        if (old !== ta) {
            $(dy).text(ta);
            old = ta;
        }
        window.setTimeout(update, 150);
    }
    

    它给了我变量(编辑,DYNA,旧)。 Editor 对象。 谢谢。

    2 回复  |  直到 14 年前
        1
  •  1
  •   Anurag    14 年前

    this 函数内部引用了您创建的匿名基函数的对象。

    使用 this.propertyName 以访问其属性。

    var ta = $(this.edit)[0].value, dy = $(this.dyna)[0].contentDocument;
    
        2
  •  2
  •   Jason McCreary    14 年前

    你为什么不直接用 this 前缀。所以 this.edit[0].value ?

    也许我错过了一些东西,因为这里已经很晚了…