将字符串的值转换为init类的名称

时间:2019-03-31 03:05:40

标签: javascript

我有这个:

var name_of_player = "Ted"
window[name_of_player] = new Player(name_of_player);

function show(player) {
    player.return_name;

我想要这样的东西:

show(name_of_player); --> Ted.return_name;

我该怎么办?

2 个答案:

答案 0 :(得分:0)

要做的和创建播放器时一样:

function show(player) {
    return window[player].return_name;
}

或者简单地:

function show(player) {
    return player;
}

答案 1 :(得分:0)

您可以从window对象访问函数内部的变量。在Player构造函数中,将参数传递为实例的return_name

function Player(name){
  this.return_name = name;
}

var name_of_player = "Ted"
window[name_of_player] = new Player(name_of_player);

function show(player) {
    return window[player].return_name;
}

console.log(show(name_of_player))