简体   繁体   English

在“旧的”上下文中使用应用或调用

[英]Use apply or call with “old” context

B = function(fn) {

    var ex_array = ['a', 'b'];

    this.b_fn = function () {
        fn.apply(what_should_be_there, ex_array);
    }

}

A = function() {

    this.a_fn = function (a, b) {
         //do sth
    }

    var b = new B(fn); 

}

Only what I would like to do is use apply with on function fn in object b , but with "old" context, I mean in this case with context of object of class A 只有我想做的是在对象b对函数fn使用apply ,但是在“旧”上下文中使用,在这种情况下,我的意思是在类A的对象上下文中A

Edit 编辑

If you want to use ex_array as an array of arguments so that apply will iterate through them, do this ( jsfiddle ): 如果要使用ex_array作为参数数组,以便apply可以遍历它们,请执行以下操作( jsfiddle ):

B = function(fn) {

    var ex_array = ['a', 'b'];

    this.b_fn = function() {
      return fn.apply(null, ex_array);  
    };

}

A = function() {

    this.a_fn = function (a, b) {
         console.log(this, a, b);
    }

    var b = new B(this.a_fn.bind(this)); 

    b.b_fn(); // => A {}, "a", "b"

}

new A();

Previous answer 先前的答案

See this working demo on jsfiddle : 在jsfiddle上查看此工作演示

B = function(fn) {

    var ex_array = ['a', 'b'];

    this.b_fn = fn.bind(null, ex_array);

}

A = function() {

    this.a_fn = function (a, b) {
         console.log(this, a);
    }

    var b = new B(this.a_fn.bind(this)); 

    b.b_fn(); // => A {}, ['a', 'b'];

}

new A();

Basically, all you need to do is bind this.a_fn with its current context. 基本上,您需要做的就是this.a_fn与当前上下文绑定。 The trick is to use .bind(null, /* args */) when making it this.b_fn , so it keeps the original A context, but allows you to pass in another parameter (in this case, ['a', 'b'] . 诀窍是在使其为this.b_fn时使用.bind(null, /* args */) ,因此它保留了原始的A上下文,但允许您传入另一个参数(在这种情况下, ['a', 'b']

Here's a solution where a_fn isn't prebound to an arguments array. 这是不将a_fn预绑定到arguments数组的解决方案。 I added some logging as demo: 我添加了一些日志作为演示:

var B = function(fn) {
  var ex_array = [ 'a', 'b' ];
  this.b_fn = function () {
    fn(ex_array);
  };
};

var A = function() {
  this.c    = 'hello world';
  this.a_fn = function(a, b) {
    console.log('a:', a);
    console.log('b:', b);
    console.log('c:', this.c);
  };
  var b = new B(Function.prototype.apply.bind(this.a_fn, this));
  b.b_fn();
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM