2017-07-19 57 views
0

我有一個對象方法a象下面這樣:如何將字符串傳遞到Javascript中的對象方法?

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,現在我想將一個字符串Hello world傳遞給對象方法a。如果不允許使用全局變量,如何將字符串傳遞給對象方法?

回答

0

如果你想打電話ef上下文那麼你需要通過fcall,寫作e.call()將等於e()

除此之外,t是指變量而不是的屬性t。您不能以這種方式設置變量,但可以將其存儲在對象中f

您可以這樣寫。

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

見下面摘錄

var f = { 
 
    a: function(e){ 
 
     e.call(); 
 
     console.log(f.a.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」 ? 
 
});

0

什麼是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 
}); 
0

爲什麼不在對象定義屬性,如:

var f = { 
 
    t: '', 
 
    a: function(e){ 
 
    e.call(); 
 
    console.log(this.t); // Here should print 「Hello world」 
 
    } 
 
}; 
 
f.a(function(){ 
 
    f.t = "Hello world"; 
 
});

1

你可能要考慮改變如下您e的返回值:

var f = { 
 
     a: function(e){ 
 
      var t = e.call();//here declare variable t 
 
      console.log(t); // Here should print 「Hello world」 
 
     } 
 
    }; 
 
    f.a(function(){ 
 
     return "Hello world";//directly return string value from anonymous function 
 
     // How to pass the string 「Hello world」 into the object method 「a」 ? 
 
    });

+0

非常優雅。這個解決方案很好地分離了「f」聲明和匿名函數:你不必知道匿名函數中'f'的內部工作。在其他解決方案中(包括我提出的方案),匿名函數必須知道,爲了傳遞字符串「Hello World」,必須設置對象f的屬性「t」的值或'this'(在這種情況下,如果您忘記將'this'添加到'e.call()',它不起作用)。 – jotaelesalinas

+0

@jotaelesalinas謝謝,我真的很受寵:) –

0

f是Java腳本對象,您可以到that.I添加屬性只是增加了ft =「Hello world」。你可以在程序中的任何地方使用ft。

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」 ? 
    }); 
相關問題