我正在尝试警告“ 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>
答案 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);