Javascript";如果;操作顺序
假设你有一个非常基本的person对象,有两个值和一个函数:Javascript";如果;操作顺序,javascript,conditional-statements,operator-precedence,Javascript,Conditional Statements,Operator Precedence,假设你有一个非常基本的person对象,有两个值和一个函数: function personObject() { this.name = 'First Name'; this.placeInLine = 1; this.setPlaceInLine = function(place) { this.placeInLine = place; } } 我们设置了如下一些变量: var john = new personObject(); var bi
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
结果:message=“约翰不在比尔面前”//因为1不小于1
---代码#2---
bill.setPlaceInLine(2);//将票据位置更改为2(而不是默认的1)
if(john.placeInLine
结果:message=“约翰在比尔面前”//因为1小于2
---代码#3---
if(john.placeInLine
结果:message=“约翰不在比尔面前”://为什么
比较后是否调用.setPlaceInLine函数?或者运行该函数的行为返回的是与john.placeInLine比较的内容?因为
setPlaceInLine
方法没有显式返回,因此返回未定义的。而1
计算为false
:undefined
转换为Number
,给出NaN
,1
当然是false
(1>NaN
也是false
,顺便说一句)
虽然可以通过使setter方法返回指定的值来解决此问题:
PersonObject.prototype.setPlaceInLine = function(place) {
return this.placeInLine = place;
}
。。。我认为最好(更干净)分别使用setter和getter(就像您的代码#2示例中那样)
作为旁注,我建议使用原型来设置对象方法(就像我在示例代码中所做的那样)。原因在中有很好的解释:基本上,对于原型,当使用this时,您将只创建一个函数实体,供所有创建的对象使用。someMethod
您将在每次调用构造函数时创建一个新函数。您正在与函数的返回值进行比较
除非您通过返回this.placeInLine实际返回值代码>它将与未定义的进行比较
总是导致错误
将代码更改为:
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;
}
}
修正了代码片段中的错误-很抱歉混淆了!!!现在我明白了。我在bill.setPlaceInLine(2)调用中尝试了一个typeof,它确实返回“undefined”,这就是比较所使用的。现在我明白了。谢谢你的澄清!快速提问-我的“person”对象只是我编的一个例子…我实际上是在从另一个库调用对象上的函数。在setter上没有返回值是通用标准吗?还是库的构建很差,应该有一个返回值?@user1607577大多数库都会返回您正在操作的对象,以便您可以执行链接操作,如bill.placeInLine().changeName(“bill”)
PersonObject.prototype.setPlaceInLine = function(place) {
return this.placeInLine = place;
}
this.setPlaceInLine = function(place) {
return this.placeInLine = place;
}
function personObject() {
this.name = 'First Name';
this.placeInLine = 1;
this.setPlaceInLine = function(place) {
this.placeInLine = place;
return place;
}
}