gpt4 book ai didi

javascript - 使用 apply 或 call 与 "old"上下文

转载 作者:行者123 更新时间:2023-11-28 07:15:16 25 4
gpt4 key购买 nike

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);

}

我唯一想做的就是在对象b中使用apply和函数fn,但是在“旧”上下文中,我在这种情况下意味着类 A

的对象上下文

最佳答案

这是一个解决方案,其中 a_fn 未预先绑定(bind)到参数数组。我添加了一些日志记录作为演示:

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();
};

关于javascript - 使用 apply 或 call 与 "old"上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30898564/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com