簡體   English   中英

Javascript“ if”操作順序

[英]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計算結果為falseundefined被轉換為Number ,給出NaN ,而1 < NaN當然也是false1 > 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM