gpt4 book ai didi

javascript - 在JS中将函数作为参数传递并访问接收函数的变量

转载 作者:行者123 更新时间:2023-11-28 18:39:08 25 4
gpt4 key购买 nike

我不确定这在 Javascript 中是否可行。我想通过传递的函数访问函数的变量(或者如果函数是通过“onend”调用传递的)。

function Outer() {

var fn;
var foo = 'this is foo';

this.bar = function(x) {
fn();
}

this.setFunction = function(f) {
fn = f;
}
}

var o = new Outer();
o.setFunction(function() {
alert(foo); //doesn't work
});

o.bar(); //want to alert 'this is foo'

最佳答案

在您的情况下,

fn 在功能上是回调。使用本地 foo 变量作为参数调用回调:

function Outer() {

var fn;
var foo = 'this is foo';

this.bar = function() {
fn(foo);
}

this.setFunction = function(f) {
fn = f;
}
}

var o = new Outer();
o.setFunction(function(foo) {
alert(foo);
});

o.bar();

关于javascript - 在JS中将函数作为参数传递并访问接收函数的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36426589/

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