You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript中使用with关键字后构造函数实例属性返回undefined的原因

问题解决:Car构造函数属性输出undefined的问题

问题原因

你在with(this)块里直接写Carprice = amount时,因为当前Car实例(也就是this)还不存在Carprice和CarColour这两个属性,JavaScript会把这些赋值操作当成创建全局变量,而不是给实例本身添加属性。所以你打印Nissan.Carprice和Nissan.CarColour时,实例上根本没有这两个属性,自然输出undefined。

正确写法

方案一:直接用this绑定属性(推荐)

这是最规范、可读性最高的写法,完全没必要用with语句:

function Car(amount, color) {
    this.Carprice = amount;
    this.CarColour = color;
}

var Nissan = new Car(10000, "red");
document.write(Nissan.Carprice); // 输出10000
document.write(Nissan.CarColour); // 输出red

方案二:非要用with的写法(不推荐)

如果坚持要用with,得先在实例上初始化这两个属性,让with块能定位到实例的属性进行赋值:

function Car(amount, color) {
    // 先在实例上声明属性
    this.Carprice = null;
    this.CarColour = null;
    with(this) {
        Carprice = amount;
        CarColour = color;
    }
}

var Nissan = new Car(10000, "red");
document.write(Nissan.Carprice); // 输出10000
document.write(Nissan.CarColour); // 输出red

额外说明

with语句在现代JavaScript开发中并不推荐使用,它会模糊作用域边界,降低代码可读性,还容易引发意外的bug,所以优先选择方案一。

内容的提问来源于stack exchange,提问作者Evan Bose

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 08:55:31