为何JavaScript构造函数代码输出0而非2?参数传递问题咨询
问题分析与解决
问题原因
你传入GameObject的是brick函数本身,而非它返回的对象。在JavaScript里,函数的length属性代表它定义时的形参数量,brick没有形参,所以gameObjectType.length的值是0,这就是输出0的核心原因。
另外你的构造函数里还存在一个小问题:positionX和positionY没有使用传入的参数,而是硬赋值为1和2,这可能不符合你的预期。
修正方案
这里提供三种可行的解决方式:
方式1:传入brick执行后的对象
创建实例时调用brick(),把它返回的对象作为参数传入:
function brick() { return { length: 2, width: 4, }; } function GameObject(positionX, positionY, gameObjectType = {}) { this.weight = 2; this.positionX = positionX; // 修正为使用传入的参数 this.positionY = positionY; // 修正为使用传入的参数 this.length = gameObjectType.length; this.width = gameObjectType.width; } // 调用brick()传入返回的对象 let example = new GameObject (4, 6, brick()); console.log(example.length); // 输出2
方式2:将brick改为直接定义对象
如果brick不需要动态生成属性,直接定义为对象即可:
// 直接定义为对象,无需函数包裹 const brick = { length: 2, width: 4, }; function GameObject(positionX, positionY, gameObjectType = {}) { this.weight = 2; this.positionX = positionX; this.positionY = positionY; this.length = gameObjectType.length; this.width = gameObjectType.width; } // 直接传入brick对象 let example = new GameObject (4, 6, brick); console.log(example.length); // 输出2
方式3:在构造函数内自动处理函数类型参数
如果需要保留brick的函数形式(比如后续要动态生成属性),可以在构造函数里判断参数类型,若为函数则自动执行:
function brick() { return { length: 2, width: 4, }; } function GameObject(positionX, positionY, gameObjectType = {}) { this.weight = 2; this.positionX = positionX; this.positionY = positionY; // 判断参数是否为函数,是则执行拿到对象 const typeData = typeof gameObjectType === 'function' ? gameObjectType() : gameObjectType; this.length = typeData.length; this.width = typeData.width; } // 直接传入brick函数即可 let example = new GameObject (4, 6, brick); console.log(example.length); // 输出2
内容的提问来源于stack exchange,提问作者Axel
相关产品推荐
相关产品推荐

