JavaScript 对象方法未更改 属性

JavaScript Object method not changing property

我正在构建一个工厂函数来管理战舰游戏的 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` 属性.

谢谢

您可以创建一个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());

您可以使用 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);