将值传递给'这个'在javascript函数中

时间:2016-09-08 20:27:08

标签: javascript

这有一种方法可以将任意值传递给"这个"在下面的foo函数中;

function foo(a){
var getThis = this;
var getA = a;

console.log("getThis:"+getThis);
console.log("\n"+a);
}

foo(5);

预期产出:

getThis: some value that I can pass
5

回答问题:

foo.call('some value that I can pass', 5);

感谢

2 个答案:

答案 0 :(得分:2)

使用applycall来调用该功能,而不是直接调用它。

foo.call("this is a string", 5);

答案 1 :(得分:1)

您可以在此处详细了解foo.call("hello", 5); foo.apply("hello", [5]); MDN。您可以通过以下方式使用不同的 class Program { static void Main(string[] args) { string results = " A 1 B 0, A 2 C 4, A 1 D 8, A 5 E 9"; string[] matches = results.Trim().Split(','); List<Match> sportResults = new List<Match>(); foreach (string match in matches) { string[] parts = match.Trim().Split(null); sportResults.Add(new Match() { Team1 = parts[0], Score1 = int.Parse(parts[1]), Team2 = parts[2], Score2 = int.Parse(parts[3])}); } sportResults.ForEach(a => Console.WriteLine(a)); } } 调用该函数:

class Match
  {
    public string Team1 { get; set; }
    public string Team2 { get; set; }

    public int Score1 { get; set; }
    public int Score2 { get; set; }

    public override string ToString()
    {
      return "Team " + Team1 + " " + Score1 + " VS " + Team2 + " " + Score2;
    }
  }