【问题标题】:Using local variables with "apply" in Javascript在 Javascript 中使用带有“应用”的局部变量
【发布时间】:2014-03-06 04:30:49
【问题描述】:

为什么“show”方法无法在此处访问“text”变量?

// @constructor A
var A = function(){

    //alerts some text variable
    this.show = function(){
       alert("Hello")
       alert(text);
  }

}

//@constructor B
var B = function(){

  //local text variable
  var text = "World";
  A.apply(this); // "show" method will get attached to B
}

var obj = new B();

//now calling show of B's object.
obj.show(); //returns error.



//Expected output
alerts "Hello"
alerts "World"

//Actual output
alerts "Hello" 
ReferenceError: text is not defined

我在这里遗漏了什么吗? B的“show”方法不应该可以访问“text”变量吗?

【问题讨论】:

    标签: javascript variables inheritance scope apply


    【解决方案1】:

    与 C++ 或 Java 不同,Javascript 没有隐式 this

    如果一个函数(如show)引用this.foo,那么只有this 的值取决于函数的调用方式。

    但是,如果show 直接引用一个变量(如foo),那么它可能意味着:

    • 一个局部变量,如果它是在函数范围内使用var 定义的;
    • 闭包中的变量,如果该函数是在另一个函数中定义的,而该函数恰好用var 定义它(闭包在函数定义时创建),
    • 否则为全局变量。

    在您的情况下,适用第三种情况。 show 无法访问 text,因为它是在完全不相关的范围内定义的。

    【讨论】:

    • 感谢..."show 无法访问文本,因为它是在完全不相关的范围内定义的。"
    【解决方案2】:

    您需要将text 声明为B 构造函数this.text = "World"; 的属性,如下所示。

    var A = function(){
    
        //alerts some text variable
        this.show = function(){
           alert("Hello")
           alert(this.text);
      }
    
    }
    
    //@constructor B
    var B = function(){
    
      //local text variable
       this.text = "World";
      A.apply(this); // "show" method will get attached to B
    }
    
    var obj = new B();
    
    //now calling show of B's object.
    obj.show(); //returns error.
    

    【讨论】:

    • 感谢苏曼博加蒂。但我知道解决方案是什么,我只是想知道为什么(这种特殊行为)会发生。
    猜你喜欢
    • 2014-02-24
    • 1970-01-01
    • 2011-08-26
    • 2016-09-06
    • 1970-01-01
    • 1970-01-01
    • 2013-05-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多