2017-04-01 109 views
-1

我想了解的對象和功能比較運營商,這是我的代碼:與布爾總是返回false

function house(roof) { 
    this.roof = roof; 
    this.roofdescrip = describehouse(); 
} 

function describehouse(){ 
    var z = this.roof; 
    x="The house has a roof."; 
    y="The house does not have a roof."; 
    if(z===true){return x;} 
    else{return y;} 

    } 

var myhouse = new house(true); 



document.write(myhouse.roofdescrip); 

總是返回

The house does not have a roof. 

我是否更改參數爲true或false 。爲什麼?

+0

Triple =比較類型。不確定這是否是問題,但是在這裏您將屋頂與布爾值進行比較? – Andromelus

+0

'describehouse'不是'myhouse'的*方法*,所以當你這樣稱呼'this'時不起作用 – Bergi

回答

0

這是因爲this運營商describehouse()功能點的窗口對象,將有roof等於undefined,試圖傳遞this作爲參數。 類似這樣的東西

function house(roof) { 
    this.roof = roof; 
    this.roofdescrip = describehouse(this); 
} 

function describehouse(that){ 
    var z = that.roof; 
    x="The house has a roof."; 
    y="The house does not have a roof."; 
    if(z===true){return x;} 
    else{return y;} 

    } 

var myhouse = new house(true); 

document.write(myhouse.roofdescrip); 
+0

describehouse函數中'this'是什麼意思? – user3054769

+0

'this'指向該方法的調用者,在您的情況下,它是全局窗口對象而非房屋對象,如果您想更清楚地看到它,請編寫{{var roof = true; }}在任何函數之外,這樣window對象的'roof'等於true,'z'將爲true –

0

問題與範圍有關。在你的情況下,this裏面describehouse函數實際上是window對象。如果您嘗試在功能內登錄this.roof,您將獲得undefinedundefined被認爲是錯誤的,這就是您總是得到相同結果的原因。

爲使您的代碼正常工作,您需要將函數綁定到您的對象,然後調用該函數。

function house(roof) { 
    this.roof = roof; 
    this.roofdescrip = describehouse.bind(this); 
} 


function describehouse(){ 
    var z = this.roof; 
    console.log(this) 
    x="The house has a roof."; 
    y="The house does not have a roof."; 
    if(z===true){return x;} 
    else{return y;} 

    } 

var myhouse = new house(true); 

document.write(myhouse.roofdescrip()); 

在這裏,我把另一種方式來做到這一點。

class House { 
    constructor(roof) { 
    this.roof = roof 
    } 

    describeHouse() { 
    const verb = this.roof ? "has" : "does not have" 
    return `The house ${verb} a roof.` 
    } 
} 

const myHouse = new House(true) 
const otherHouse = new House(false) 
console.log(myHouse.describeHouse()) // "The house has a roof." 
console.log(otherHouse.describeHouse()) // "The house does not have a roof."