我正在尝试理解对象和函数,这是我的代码:
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 :(得分:0)
那是因为Match_number,Winner,Winner_Score,Loser_score
1,Red,2,1
2,Blue,3,2
3,Red,4,1
etc...
函数中的this
运算符指向窗口对象,describehouse()
等于roof
,请尝试传递{{1}作为参数。
像这样的东西
undefined
答案 1 :(得分:0)
问题与范围有关。在您的情况下,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."