如何在Javascript中将字符串传递到对象方法中?

如何在Javascript中将字符串传递到对象方法中?,javascript,Javascript,我有一个对象方法a,如下所示: var f = { a: function(e){ e.call(); console.log(t); // Here should print “Hello world” } }; f.a(function(){ f.a.t = "Hello world"; // How to pass the string “Hello world” into the object method “a” ? });

我有一个对象方法
a
,如下所示:

var f = {
   a: function(e){
       e.call();
       console.log(t);    // Here should print “Hello world”
   }
};
f.a(function(){
    f.a.t = "Hello world";
    // How to pass the string “Hello world” into the object method “a” ?
});
e
是一个匿名函数。我调用
e
,现在我想把一个字符串
helloworld
传递到对象方法
a
。如果不允许使用全局变量,如何将字符串传递到object方法中?

请参见下面的代码段

var f={
a:功能(e){
e、 call();
console.log(f.a.t);//这里应该打印“Hello world”
}
};
f、 a(函数(){
f、 a.t=“你好,世界”;
//如何将字符串“helloworld”传递到对象方法“a”中?

});什么是
t
的范围?如果它是
f
的一个属性,请编写以下内容:

var f = {
    a: function(e){
        e.call();
        console.log(this.t); // this line changed
    }
};
f.a(function(){
    f.t = "Hello world"; // this line changed
});

为什么不在对象中定义属性,如:

var f={
t:“,
a:功能(e){
e、 call();
console.log(this.t);//这里应该打印“Hello world”
}
};
f、 a(函数(){
f、 t=“你好,世界”;

});
如果要在
f
的上下文中调用
e
,则需要将
f
传递给
call
,写入
e。call()
将等于
e()

除此之外,
t
指的是一个变量,而不是
a
的属性
t
。不能这样设置变量,但可以将其存储在对象
f

你会那样写的

var f = {
   a: function(e){
       e.call(this);
       console.log(this.t);
   }
};
f.a(function(){
    this.t = "Hello world";
});

您可能想考虑更改<代码> e <代码>的返回值如下:

var f={
a:功能(e){
var t=e.call();//这里声明变量t
console.log(t);//这里应该打印“Hello world”
}
};
f、 a(函数(){
返回“Hello world”;//直接从匿名函数返回字符串值
//如何将字符串“helloworld”传递到对象方法“a”中?

});f是java脚本对象,您可以向其添加属性。我刚刚添加了f.t=“Hello world”。您可以在程序中的任何地方使用f.t,只要您有f范围

var f = {
       a: function(e){
           e.call();
           console.log(f.t);    // Here should print “Hello world”
       }
    };
    f.a(function(){
        f.t = "Hello world";
        // How to pass the string “Hello world” into the object method “a” ?
    });

非常优雅。此解决方案很好地将
f
的声明与匿名函数解耦:您不必知道匿名函数中
f
的内部工作。在其他解决方案中(包括我提出的解决方案),匿名函数必须知道,为了传递字符串
“Hello world”
,它必须设置object
f
this
(在这种情况下,如果忘了将
this
添加到
e.call()
,它将不起作用).