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

在调用堆栈中较高的方法中访问“this”对象

  •  1
  • erikkallen  · 技术社区  · 17 年前

    我有以下JavaScript:

    function b() {
        alert(arguments.caller[0]);
    }
    
    function X(x) {
        this.x = x;
    }
    
    X.prototype.a = function(i) {
        b();
    }
    
    new X(10).a(5);
    

    3 回复  |  直到 17 年前
        1
  •  1
  •   balpha    17 年前

    可以将调用方作为参数传递给函数:

    function b(caller) {
        alert(caller.x);
    };
    
    function X(x) {
        this.x = x;
    };
    
    X.prototype.a = function(i) {
        b(this);
    };
    
    new X(10).a(5);
    

    请注意,arguments.caller在JS 1.3中被弃用,在JS 1.5中被删除。

        2
  •  1
  •   James    17 年前
    function b() {
        alert(this.x);
    }
    
    function X(x) {
        this.x = x;
    }
    
    X.prototype.a = function(i) {
        b.call(this); /* <- call() used to specify context */
    }
    
    new X(10).a(5);
    
        3
  •  0
  •   Jeff Meatball Yang    17 年前

    通过将对函数b的调用包装在匿名函数中,您引入了一种间接级别。如果可能,您应该直接设置它。

    function b() {
      alert(this.x);  // 10
      alert(arguments[0]); // 5
    }
    
    function X(x) {
      this.x = x; /* alternatively, set this.x = arguments to capture all arguments*/
    }
    
    X.prototype.a = b;
    
    new X(10).a(5);
    

    推荐文章