【问题标题】:Comparison operator with boolean always returning false带有布尔值的比较运算符总是返回 false
【发布时间】:2017-04-01 20:28:38
【问题描述】:

我正在尝试理解对象和函数,这是我的代码:

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。为什么?

【问题讨论】:

  • Triple = 也比较类型。不确定这是否是问题所在,但在这里您将屋顶与布尔值进行比较?
  • describehouse 不是myhouse方法,所以this 在你这样称呼它时不起作用

标签: javascript html string comparison string-comparison


【解决方案1】:

这是因为describehouse() 函数中的this 运算符指向的窗口对象将具有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”指向什么?
  • 'this' 指向方法的调用者,在你的情况下它是全局窗口对象而不是房子对象,如果你想更清楚一点,写 {{ varroof = true ; }} 在任何函数之外,这样窗口对象的 'roof' 将等于 true 并且 'z' 将是 true
【解决方案2】:

问题与范围有关。在您的情况下,describehouse 函数中的 this 实际上是 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."

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-23
    • 2017-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多