メモ-割り当てと演算の順序

1861 ワード

var i=1;i=i++;alert(i);
なぜi=1?
------------------------------------------------------------------------------------------------------------------------------
ECMAScript® Language Specification

11.13.1 Simple Assignment ( = )


The production AssignmentExpression : LeftHandSideExpression =AssignmentExpression is evaluated as follows:
Let lref be the result of evaluating LeftHandSideExpression. Let rrefbe the result of evaluating AssignmentExpression. Let rval beGetValue(rref). Throw a SyntaxError exception if the followingconditions are all true: Type(lref) is Reference is trueIsStrictReference(lref) is true Type(GetBase(lref)) is EnvironmentRecord GetReferencedName(lref) is either "eval"or "arguments" CallPutValue(lref, rval). Return rval. NOTE When an assignment occurswithin strict mode code, its LeftHandSide must not evaluate to anunresolvable reference. If it does a ReferenceError exception isthrown upon assignment. The LeftHandSide also may not be a referenceto a data property with the attribute value {[[Writable]]:false}, toan accessor property with the attribute value {[[Set]]:undefined}, norto a non-existent property of an object whose [[Extensible]] internalproperty has the value false. In these cases a TypeError exception isthrown.
この2つに注意してください.
Let rval be GetValue(rref).Call PutValue(lref, rval).
すなわち,まずi++が実行され,このときiは2に割り当てられ,1が返され,その後iに1が与えられ,最終iは1となる.
簡単に言えば、
var i = 1; i = i++; 

に等しい
var i, temp; // temp is "rval", which may not be an actual variable. i = 1; temp = i; i = i + 1; i = temp;