将 "this" 更改为名称 space 中的变量名称

Change "this" to a variable name within name space

我正在做一个需要用名字space完成的项目。当我需要将 "this" 更改为 actually 时,我遇到了一些麻烦 变量名。

因此

我创建了一个名字 space $work。 然后是一个名为$work.Guess的class(后来我改名为"game") 然后是一个名为point的方法。 (该方法从按钮上的 onclick 触发)

我曾尝试将 "this" 更改为其他内容。在我看来,它应该是 game.point,但这没有用。所以我然后尝试使用 "var point"。他们都没有使用按钮的 onclick 事件。然后我尝试使用我认为可以代替 "this" 的每个名称来访问该方法。失败。

这是示例代码。

var $work = {};
$work.Guess = function() {

  this.point = function() {
    alert('found' + " " + 'point');
  }

}

var game = new $work.Guess;
<form name="foo">
  <h2>Check scores</h2>
  <input type="button" value="Check points" onclick='game.point();' />
  <br />
</form>

试试这个

var $work = {};
$work.Guess = {
    point: function() {
        alert('found' + " " + 'point');
    }
};

var game = $work.Guess;

更新:

不知道反对票是干什么用的。无论哪种方式,上面的工作都很好。

<form name="foo">
  <h2>Check scores</h2>
  <input type="button" value="Check points" onclick='game.point();' />
  <br />
</form>

你想去掉这里的 this 是对的。以这种方式向对象添加实例方法是一种浪费,因为它会为每个对象创建一个新的函数副本。在 Javascript 中,"class method inheritance"(通常称为)是通过原型完成的:

$work.Guess = function () { };
$work.Guess.prototype.point = function () {
    alert('found point');
};

var game = new $work.Guess();
game.point();

如果我不在这里指出更好的 ES6 class syntax,那就太不对了。