【问题标题】:what does this refer to in a javascript private method这在 javascript 私有方法中指的是什么
【发布时间】:2011-01-16 14:43:05
【问题描述】:

使用以下代码:

function Node(){
 ....
 function foo(request){
        for (var name in this ) {
            log(name +" is "+this[name]);
            if(!(name == 'all' || typeof this[name] == 'function')){
                request[name] = this[name];
            }
        }
        return ...
    };
}

我很惊讶当私有函数 foo 被调用时 this 似乎并没有引用包含对象(Node 的一个实例)。这是为什么呢?

当然我可以有类似的东西:

 function Node(){
      var ref = this;
      ....
 }

并在foo 中将ref 用作this,但是有没有办法声明this 是对包含对象的引用的私有方法?

【问题讨论】:

    标签: javascript methods private


    【解决方案1】:

    'this'是指调用函数的对象,默认是'window'。

    使用 foo.apply(this, ...) 或 foo.call(this, ...) 调用 foo,这样 foo 中的 'this' 指的是调用 foo 的 'this'。

    我使用的约定(避免 .apply 和 .call)是:

    var me = this;
    
    function foo()
    {
        // use 'me'
    }
    

    顺便说一句,“Me”是 VB.NET 中“this”的关键字。

    【讨论】:

    • "'this' 指的是用于调用函数的对象",但我从 Node 中的公共函数调用 foo ( this.publicFoo = function(){ ... foo(); 。 ..};)。那这怎么还是指window呢?干杯
    • 'this' 指的是“.”左侧的对象。当一个方法被调用时。但如果调用时不带“.” (例如, foo();) 那么它意味着 window.foo();在哪里定义并不重要,重要的是如何调用。
    【解决方案2】:

    “this”的实现不正确,但并未“修复”,导致所有的混乱和变通方法。

    您的var ref=this; 正是您维护对对象的引用以供其公共/私有成员使用的方式。 Douglas Crockford (google it) 使用var that=this;。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-07
      • 2017-07-07
      • 2019-02-15
      • 1970-01-01
      • 2015-12-07
      • 2020-05-14
      • 2010-09-09
      • 2014-08-26
      相关资源
      最近更新 更多