【问题标题】:JavaScript Object method not changing propertyJavaScript Object 方法不改变属性
【发布时间】:2021-10-25 08:54:23
【问题描述】:

我正在构建一个工厂函数来管理战舰游戏的 Ship 对象。到目前为止,我有以下内容:

    const Ship = (name, length, orientation = 'horizontal') => {
  let sunk = false;
  const hits = Array(length).fill(false);

  const hit = (position) => {
    if (position <= hits.length) hits[position] = true;
  };

  function sink() {
    sunk = true;
  }

  return {
    name,
    length,
    orientation,
    sunk,
    hits,
    hit,
    sink,
  };
};

我正在测试sink() 方法以将沉没属性布尔值从false 更改为true。但是,每当我跑步时:

example.sink() example.sunk 沉没总是假的。

我哪里错了?

由于某种原因,hit() 方法改变了 hits 属性fine. Butsink()is not altering thesunk` 属性。

谢谢

【问题讨论】:

  • 你是如何调用这个方法的?
  • sunk 是一个布尔值,而不是像 hits 这样的数组引用。 Ship 返回的对象不会被重新评估,因此值将始终相同。
  • 谢谢,那么我怎样才能实现我想要做的呢?
  • 您可以为sunk 属性创建gettersetter
  • @LearningPython 我可能会退后一步,找到一些好的 JS OOP 教程,然后决定你想采用哪种 JS OOP 方法。有几种方法可以解决这个问题。

标签: javascript object methods tdd


【解决方案1】:

您可以使用getters 检索值:

const Ship = (name, length, orientation = 'horizontal') => {
  let sunk = false;
  const hits = Array(length).fill(false);

  const hit = position => {
    if (position <= hits.length) hits[position] = true;
  };

  function sink() {
    sunk = true;
  }

  return {
    name,
    length,
    orientation,
    hit,
    sink,
    // get values using getters
    get sunk() { return sunk; },
    get hits() { return hits; },
  };
};

const someShip = Ship(`ss something`, 100, `vertical`);
someShip.sink();
console.log(someShip.sunk);

【讨论】:

  • 谢谢,这正是我想要的。我忘记使用吸气剂了!
【解决方案2】:

你可以创建一个API方法来访问本地的sunk方法

const Ship = (name, length, orientation = "horizontal") => {
  let sunk = false;
  const hits = Array(length).fill(false);

  const hit = (position) => {
    if (position <= hits.length) hits[position] = true;
  };

  function sink() {
    sunk = true;
  }

  function getSunk() {
    return sunk;
  }

  return {
    name,
    length,
    orientation,
    hits,
    hit,
    sink,
    getSunk,
  };
};

const ship = Ship("a", 10);
console.log(ship.getSunk());
ship.sink();
console.log(ship.getSunk());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多