0

当我运行时++this.get('votes'),我收到以下错误消息

Uncaught ReferenceError: Invalid left-hand side expression in prefix operation.

我得到了同样的错误信息++(this.get('votes'))

我能够解决这个问题,this.get('votes') + 1但我不知道为什么前缀运算符不起作用。

为什么不应该this.get('votes')评估为 0 然后变为 1 并返回值 1?


上下文中的原始代码:

var Comment = Backbone.Model.extend({
  initialize: function(message) {
     this.set({votes: 0, message: message});
  },
  upvote: function(){
    // Set the `votes` attribute to the current vote count plus one.
    this.set('votes', ++this.get('votes')); 
  }
}
var comment = new Comment('This is a message');
comment.upvote();
4

1 回答 1

4

根本问题是您不能分配给this.get('votes'); 即,某种形式:

f() = x;

无效,因为f()不是左值。

如果您检查specs,您会发现它++x与以下内容大致相同:

x = x + 1

并且您不能为函数调用分配值。你真的想说:

this.get('votes') = this.get('votes') + 1;

那不是JavaScript。

于 2017-11-18T22:27:06.117 回答