[英]Javascript “if” Order of Operations
因此,假设您有一个具有两个值和一个函数的基本人对象:
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";
结果:message =“约翰不在比尔之前”; //因为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";
结果:message =“约翰在比尔之前”; //因为1小于2;
-代码#3 ---
if(john.placeInLine < bill.setPlaceInLine(2)) message = "John is before Bill";
else message = "John is not before Bill";
结果:message =“约翰不在比尔之前”://为什么?
比较之后是否调用.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;
}
...我认为最好分别使用setter和getter(更干净),就像在代码#2示例中一样。
作为附带说明,我建议使用原型来设置对象方法(就像我在示例代码中所做的那样)。 这个问题的原因在这个答案中得到了很好的解释:基本上,使用原型时,您将只创建一个由所有创建的对象使用的单个Function实体,当使用this.someMethod
时,每次调用构造函数时,您都将创建一个新Function。
您正在与函数的返回值进行比较。
除非您实际上通过return this.placeInLine;
返回一个值return this.placeInLine;
它将与undefined
结果进行比较,始终导致false
。
将代码更改为此:
this.setPlaceInLine = function(place) {
return this.placeInLine = place;
}
setPlaceInLine不返回任何内容。 而且没有任何事物的值小于1。您可以更新setPlaceInLine以返回值:
function personObject() {
this.name = 'First Name';
this.placeInLine = 1;
this.setPlaceInLine = function(place) {
this.placeInLine = place;
return place;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.