与布尔总是返回false
我想了解的对象和功能比较运营商,这是我的代码:与布尔总是返回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 。为什么?
这是因为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);
describehouse函数中'this'是什么意思? – user3054769
'this'指向该方法的调用者,在您的情况下,它是全局窗口对象而非房屋对象,如果您想更清楚地看到它,请编写{{var roof = true; }}在任何函数之外,这样window对象的'roof'等于true,'z'将为true –
问题与范围有关。在你的情况下,this
里面describehouse
函数实际上是window
对象。如果您尝试在功能内登录this.roof
,您将获得undefined
。 undefined
被认为是错误的,这就是您总是得到相同结果的原因。
为使您的代码正常工作,您需要将函数绑定到您的对象,然后调用该函数。
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."
Triple =比较类型。不确定这是否是问题,但是在这里您将屋顶与布尔值进行比较? – Andromelus
'describehouse'不是'myhouse'的*方法*,所以当你这样称呼'this'时不起作用 – Bergi