Javascript“if”操作顺序

时间:2012-10-22 15:12:16

标签: javascript conditional-statements operator-precedence

所以假设你有一个真正基本的人物对象,有两个值和一个函数:

function personObject() {
    this.name = 'First Name';
    this.placeInLine = 1;
    this.setPlaceInLine = function(place) {
        this.placeInLine = place;
    }
}

我们设置了一些像这样的变量:

var john = new personObject();
var bill = new personObject();
var message = "";

现在看看下面的三个代码片段......

---代码#1 ---

if(john.placeInLine < bill.placeInLine) message = "John is before Bill";
else message = "John is not before Bill";

结果:消息=“约翰不在比尔之前”; //因为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";

结果:消息=“约翰在比尔之前”; //因为1小于2;

---代码#3 ---

if(john.placeInLine < bill.setPlaceInLine(2)) message = "John is before Bill";
else message = "John is not before Bill";

结果:消息=“约翰不在比尔之前”://为什么?

比较后是否调用.setPlaceInLine函数?或者是运行该函数的行为返回的东西然后被比较为john.placeInLine?

3 个答案:

答案 0 :(得分:8)

因为setPlaceInLine方法没有显式返回,因此返回undefined1 < undefined评估为falseundefined转换为Number,提供NaN1 < NaN肯定是false({ {1}}也是1 > NaN,顺便说一下。

虽然你可以通过让你的setter方法返回指定的值来解决这个问题:

false

...我认为单独使用setter和getter更好(更干净)(比如代码#2示例)。

作为旁注,我建议使用原型来设置对象方法(就像我在我的示例代码中所做的那样)。其原因在this answer中得到了很好的解释:基本上使用原型,您将只创建一个由所有创建的对象使用的Function实体,当使用PersonObject.prototype.setPlaceInLine = function(place) { return this.placeInLine = place; } 时,每次创建一个新的Function时构造函数被调用。

答案 1 :(得分:1)

您正在与函数的returnvalue进行比较。

除非您实际通过return this.placeInLine;返回值,否则它将与undefined进行比较,始终生成false

将您的代码更改为:

this.setPlaceInLine = function(place) {
    return this.placeInLine = place;
}

答案 2 :(得分:-1)

setPlaceInLine不返回任何内容。并且没有评估为小于1。 您可以更新setPlaceInLine以返回值:

function personObject() {
    this.name = 'First Name';
    this.placeInLine = 1;
    this.setPlaceInLine = function(place) {
        this.placeInLine = place;
        return place;
    }
}