Javascript:对象和函数......有人可以解释为什么这不起作用?

时间:2017-02-25 09:35:30

标签: javascript

我尝试了一段代码,但它似乎无法发挥作用。 有人可以告诉我我在这里失踪了,提前谢谢!

的javascript

var entity = function (type, w, h, c, kickSpeed, accuracy, power) {
    var entity = {};
    entity.type = type;
    entity.appearance = {
        w : w,
        h : h,
        c : c
    };
    entity.attribute = {
        kickSpeed : kickSpeed,
        accuracy : accuracy,
        power : power
    };
    return entity;
};

var spawnPlayer = function () {
    var player = {};
    entity("player", 50, 50, "green", 10, 1, 10);
    entity = player;
    ctx.fillRect(1, 1, player.appearance.w, player.appearance.h);
};
spawnPlayer();

此代码中的问题是无法找到player.appearance对象。

4 个答案:

答案 0 :(得分:1)

您忘了分配权利。

player = entity("player", 50, 50, "green", 10, 1, 10);

答案 1 :(得分:1)

只需输入此行

var player = entity("player", 50, 50, "green", 10, 1, 10);

和卸妆

entity=player 

答案 2 :(得分:1)

您没有将正在返回值的实体函数分配给播放器变量,因此永远不会定义它。您应该阅读variable scopes

var entity = function (type, w, h, c, kickSpeed, accuracy, power) {
    var entity = {};
    entity.type = type;
    entity.appearance = {
        w : w,
        h : h,
        c : c
    };
    entity.attribute = {
        kickSpeed : kickSpeed,
        accuracy : accuracy,
        power : power
    };
    return entity;
};

var spawnPlayer = function () {
    var player = entity("player", 50, 50, "green", 10, 1, 10);
    ctx.fillRect(1, 1, player.appearance.w, player.appearance.h);
};
spawnPlayer();

这是JSfiddle,它带有一个警告来显示它的工作情况。

https://jsfiddle.net/5u8bvst0/

答案 3 :(得分:1)

您没有向玩家对象分配任何内容

var spawnPlayer = function () {
  // here you define a new variable
  var player = {};
  // then you execute the function but the result are gone
  entity("player", 50, 50, "green", 10, 1, 10);
  // at the end you destroy the function definition assigning an empty object to it
  entity = player;
  ...
};

相反,你应该:

var spawnPlayer = function () {
  //execute the entity and assign to player
  var player = entity("player", 50, 50, "green", 10, 1, 10);
  //do whatever
};