[英]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
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();
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.