0 javascript operator-precedence conditional-statements
所以假设你有一个非常基本的人物对象,有两个值和一个函数:
function personObject() {
this.name = 'First Name';
this.placeInLine = 1;
this.setPlaceInLine = function(place) {
this.placeInLine = place;
}
}
Run Code Online (Sandbox Code Playgroud)
我们设置了一些这样的变量:
var john = new personObject();
var bill = new personObject();
var message = "";
Run Code Online (Sandbox Code Playgroud)
现在看看下面的三个代码片段......
---代码#1 ---
if(john.placeInLine < bill.placeInLine) message = "John is before Bill";
else message = "John is not before Bill";
Run Code Online (Sandbox Code Playgroud)
结果:消息="约翰不在比尔之前"; //因为1不小于1
---代码#2 ---
bill.setPlaceInLine(2); // change Bill's place to 2 (instead of default of 1)
if(john.placeInLine < bill.placeInLine) message = "John is before Bill";
else message = "John is not before Bill";
Run Code Online (Sandbox Code Playgroud)
结果:消息="约翰在比尔之前"; //因为1小于2;
---代码#3 ---
if(john.placeInLine < bill.setPlaceInLine(2)) message = "John is before Bill";
else message = "John is not before Bill";
Run Code Online (Sandbox Code Playgroud)
结果:消息="约翰不在比尔之前"://为什么?
是否在比较后调用.setPlaceInLine函数?或者是运行该函数的行为返回的东西然后被比较为john.placeInLine?
因为setPlaceInLine方法没有显式返回,因此返回undefined.而1 < undefined计算结果为false:undefined被转换到Number,给予NaN和1 < NaN肯定false(1 > NaN是false太,顺便说一句).
虽然您可以通过使您的setter方法返回指定的值来解决此问题:
PersonObject.prototype.setPlaceInLine = function(place) {
return this.placeInLine = place;
}
Run Code Online (Sandbox Code Playgroud)
...我认为单独使用setter和getter更好(更干净)(比如代码#2示例).
作为旁注,我建议使用原型来设置对象方法(就像我在我的示例代码中所做的那样).这个问题的原因在这个答案中得到了很好的解释:基本上使用原型,您将只this.someMethod创建一个由所有创建的对象使用的Function实体,每次调用构造函数时都会创建一个新的Function.