编程语言
首页 > 编程语言> > Javascript setter返回值而不进行验证

Javascript setter返回值而不进行验证

作者:互联网

JavaScript setter更新引用的内部值,但返回值不正确.

var Game = 
{   
    get points() {
        return this._points;
},

    set points(x){        
       x = Math.min(x,25);

       this._points = x;   
       return this._points;
    }
};

Game.points = 10 ;

console.log(Game.points); // outputs 10

var updatedPoints = (Game.points = 60);

console.log(updatedPoints); // outputs 60
console.log(Game.points); // outputs 25

‘updatedPoints’的预期价值是25!

知道为什么会发生这种情况吗?你能否建议是否有办法解决这个问题?

解决此问题的原因:确保JS代码按预期执行,可维护性!

解决方法:

JavaScript simple assignement(=)根据规范(11.13.1)返回正确的值.此行为忽略了setter中发生的任何验证.

从规格:

The production AssignmentExpression : LeftHandSideExpression =
AssignmentExpression is evaluated as follows:

  1. Let lref be the result of evaluating LeftHandSideExpression.
  2. Let rref be the result of evaluating AssignmentExpression.
  3. Let rval be GetValue(rref).
  4. Throw a SyntaxError exception if the following conditions are all true:
    • Type(lref) is Reference is true
    • IsStrictReference(lref) is true
    • Type(GetBase(lref)) is Environment Record
    • GetReferencedName(lref) is either “eval” or “arguments
  5. Call PutValue(lref, rval).
  6. Return rval.

所以没有办法按照设计“修复”你的问题.检查Game.points就足够了.

标签:javascript,javascript-objects,getter-setter,ecmascript-5,javascript-engine
来源: https://codeday.me/bug/20190825/1717286.html