【问题标题】:Grouping methods without losing the use of the this keyword [duplicate]在不丢失 this 关键字使用的情况下分组方法[重复]
【发布时间】:2018-11-24 13:01:50
【问题描述】:

在下面的代码中,如何让this 关键字绑定到Square

Square.prototype.is = {
  king: function () { this.piece === "K" }
  queen: function () { this.piece === "Q" }
  ...
};

我知道我以后可以使用call/apply,但重点是从

this.isKing()

this.is.king()

使其更具可读性(也将方法组合在一起)

this.is.king.apply(this)

似乎是倒退了一步。

【问题讨论】:

  • this 指的是什么? this 引用 Chess 实例或 this 引用其他对象?
  • 我编辑了我的帖子,问题中的课程名为 Square 而不是 Chess。所有this 关键字都引用Square 实例
  • 如果你在国王和王后 fns 上都返回this 怎么办
  • 抱歉,我不太明白你的意思。你的意思是第一个代码块中的方法?问题是从 Square.prototype.isKing = function() { return this.piece === "K"} 到 Square.prototype.is = { king: function() { return this.piece === "K" } } 更改 this 键所指的内容。在第一个示例中,它指的是 Square 实例,在第二个示例中,它指的是 Square.prototype.is 对象。我可能回答错了你的第一个问题,很抱歉造成混乱

标签: javascript methods this grouping


【解决方案1】:

我建议使用ES6 arrow functions。这是现在所有主要浏览器都支持的语法。使用箭头函数允许我们利用外部作用域的this

一个使用Class的例子:

class Square {
  constructor(){
    this.piece = null;
    this.is = {
      king: () => this.piece === "K",
      queen: () => this.piece === "Q"
    }
  }
};

const square = new Square();
square.piece = 'K';

console.log(square.is.king());
console.log(square.is.queen());

如果你决定使用 ES5 语法:

var Square = function Square() {
  var _this = this;
  this.piece = null;
  this.is = {
    king: function() { return _this.piece === "K" },
    queen: function() { return _this.piece === "Q" }
  };
};


var square = new Square();
square.piece = 'K';

console.log(square.is.king());
console.log(square.is.queen());

最后,根据@Bergi 的评论,这里还有一种方法,使用箭头函数和对象,没有任何Classes。

const Square = function Square() {  
  this.piece = null;
  this.is = {
    king: () => this.piece === "K",
    queen: () => this.piece === "Q"
  };
};


const square = new Square();
square.piece = 'K';

console.log(square.is.king());
console.log(square.is.queen());

【讨论】:

  • 我有很多方法。我的class Square 块会有几百行代码。你仍然建议这样做吗?将 .prototype 定义方法的方式和类方式结合起来是一种选择吗?
  • 在这两种方法中,基于 ES6 类的方法似乎不太冗长,尽管它们的长度非常相似。
  • 这根本不需要classes,您的方法的主要特点是在构造函数范围内创建的箭头函数。
  • @Bergi 是真的。我添加了一种更简化的方法。还清理了 ES5 示例...
  • 我只是想让您将第一句从“我建议使用 ES6 类。”修改为“我建议使用 ES6 箭头函数。" :-)
【解决方案2】:

我知道这并不能直接回答您的问题,但第三方库中常见的 is 函数通常具有以下签名:is(type)

以这种方式,你可以这样写:

square.prototype.is = function(type) {
  switch (String(type).toLowerCase()) {
    case "king": return this.piece === "K";
    case "queen": return this.piece === "Q";
    default: return false;
  }
}

假设类型是String。但它可以在Object 中定义的Number 充当Enum

我希望您不会考虑这个题外话,因为它可以作为考虑替代方法的解决方案:)

【讨论】:

  • +1,这是一个比要求的更好的解决方案:-)
猜你喜欢
  • 2015-08-31
  • 1970-01-01
  • 2014-06-11
  • 1970-01-01
  • 1970-01-01
  • 2015-05-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多