我正在尝试提醒“ 70”和“约翰”,但我收到了提醒“ [对象对象]”

时间:2018-10-02 03:03:58

标签: javascript

我正在尝试警告“ 70”和“约翰”,但我收到了警报“ [对象对象]”。我不确定为什么。

<p>
<script>
var Car = function(maxSpeed, driver) {

  this.maxSpeed = maxSpeed;
  this.driver = driver;

}

var myCar = new Car(70, "John");
window.alert(myCar);
</script>
</p>

https://js.do/code/244719

3 个答案:

答案 0 :(得分:1)

window.alert(myCar.maxSpeed+"and"+ myCar.driver);

答案 1 :(得分:1)

使用JSON.stringfy

var Car = function(maxSpeed, driver) {

  this.maxSpeed = maxSpeed;
  this.driver = driver;

}

var myCar = new Car(70, "John");
window.alert(JSON.stringify(myCar))

答案 2 :(得分:0)

另一种选择是通过设置toString方法来设置对象在作为字符串调用时应显示的内容。除非您知道自己在做什么,否则不一定建议这样做,但是该示例很合适:

var Car = function(maxSpeed, driver) {

  this.maxSpeed = maxSpeed;
  this.driver = driver;
  this.toString = () => [this.maxSpeed,this.driver].join(' and ')
}

var myCar = new Car(70, "John");
window.alert(myCar);