代码之家  ›  专栏  ›  技术社区  ›  Gwater17

为什么我不能在函数调用之前使用前缀运算符?

  •  0
  • Gwater17  · 技术社区  · 9 年前

    当我跑步时 ++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();
    
    1 回复  |  直到 9 年前
        1
  •  4
  •   mu is too short    9 年前

    根本的问题是,您无法将 this.get('votes')

    f() = x;
    

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

    如果你检查 specs ,你会看到的 ++x 大致等同于:

    x = x + 1
    

    你不能给函数调用赋值。你真的想说:

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

    这不是JavaScript。