[英]Can I pass this function to another function in Javascript?
I wrote this, but not work 我写了这个,但是没用
Can javascript function pass self to other function javascript函数可以将自身传递给其他函数吗
Can I also access the variable in the caller function? 我还可以在调用者函数中访问变量吗?
function caller()
{
var variable=123;
calledfunction(this);
}
function calledfunction(caller)
{
console.log(caller.variable);
}
caller();
Change var variable
in the assignment to this.variable
: 将赋值中的
var variable
更改为this.variable
:
function caller()
{
this.variable=123;
calledfunction(this);
}
function calledfunction(caller)
{
console.log(caller.variable);
}
caller();
In this case caller
is not really generating a new instance/scope so this
is actually global which is bad. 在这种情况下,
caller
并没有真正生成新的实例/作用域,因此this
实际上是全局的,这很不好。 It would be better to create a new empty object and use that to hold data instead of using this
. 最好创建一个新的空对象,并使用它来保存数据,而不要使用
this
。
function caller()
{
var data = {};
data.variable=123;
calledfunction(data);
}
function calledfunction(values)
{
console.log(values.variable);
}
caller();
Alternatively you can use a closure in this case by putting calledfunction
inside caller
: 另外,在这种情况下,可以通过将
calledfunction
caller
calledfunction
放在caller
calledfunction
来使用闭包:
function caller()
{
var variable=123;
calledfunction();
function calledfunction()
{
console.log(variable);
}
}
caller();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.