最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - right to left evaluation, left to right chain methods - Stack Overflow

programmeradmin4浏览0评论

The expression inside the following function is evaluated right to left

function foo(){

var a = b = c;

}

so it's like it was typed this way

var a = (b = 0)

However, when methods are chained together, they are read left to right. The methods in this object...

var obj = {
   value: 1,
   increment: function () {
       this.value += 1;
       return this;
  },
  add: function (v) {
      this.value += v;
     return this;
  },
  shout: function () {
      alert(this.value);
  }
};

can be called like this, evaluated left to right

obj.increment().add(3).shout(); // 5

// as opposed to calling them one by one

obj.increment();
obj.add(3);
obj.shout(); // 5

So, I think I know when to read left to right and right to left, but is there a rule that I need to know which I don't know?

The expression inside the following function is evaluated right to left

function foo(){

var a = b = c;

}

so it's like it was typed this way

var a = (b = 0)

However, when methods are chained together, they are read left to right. The methods in this object...

var obj = {
   value: 1,
   increment: function () {
       this.value += 1;
       return this;
  },
  add: function (v) {
      this.value += v;
     return this;
  },
  shout: function () {
      alert(this.value);
  }
};

can be called like this, evaluated left to right

obj.increment().add(3).shout(); // 5

// as opposed to calling them one by one

obj.increment();
obj.add(3);
obj.shout(); // 5

So, I think I know when to read left to right and right to left, but is there a rule that I need to know which I don't know?

Share Improve this question asked Nov 23, 2012 at 23:56 BrainLikeADullPencilBrainLikeADullPencil 11.7k24 gold badges82 silver badges138 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 8

Rule is called 'operator associativity' and is, along with operator precedence, a property of every operator (arithmetic, member access, be it unary or binary, etc.) in most of languages. Associativity is usually defined by language specs, and can often be found in books, tutorials, cheatsheets, and so on. One of first google results for javascript is here: http://www.javascriptkit./jsref/precedence_operators.shtml

发布评论

评论列表(0)

  1. 暂无评论