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

使用JavaScript Function构造函数时如何正确传递并使用参数?

问题分析与解决

问题根源

你用模板字符串(反引号)定义Function构造函数的代码体时,${this.radius}会在创建Circle1构造函数的阶段就被立即求值,此时this指向全局对象(浏览器中是window,Node.js中是global),全局对象没有radius属性,所以插值结果是undefined。最终draw函数里的console.log参数被固定为drawing circle with radius undefined,和后续实例的radius无关。

另外,你调用new Circle1(5,10)时只传了两个参数,第三个centerY会是undefined,但这不是导致radius输出undefined的核心原因。

修正方案

方案1:改用普通字符串定义Function代码体,使用字符串拼接

将Function构造函数的第二个参数换成单引号或双引号包裹的普通字符串,让draw函数内部的代码在调用时才执行:

const Circle1 = Function('radius,centerX,centerY', `
this.radius = radius;
this.centerX = centerX;
this.centerY = centerY;
this.draw = function(){
  console.log('drawing circle with radius ' + this.radius);
};
`);

const mycircle = new Circle1(5,10,15); // 可补全第三个参数,也可留空
mycircle.draw(); // 输出:drawing circle with radius 5

方案2:让draw函数内部使用模板字符串(避免提前解析)

如果想在draw里用模板字符串,需要确保它是draw函数内部的代码,而非创建Circle1时被解析。可以通过转义内部的反引号和插值符号实现:

const Circle1 = Function('radius,centerX,centerY', `
this.radius = radius;
this.centerX = centerX;
this.centerY = centerY;
this.draw = function(){
  console.log(\`drawing circle with radius \${this.radius}\`);
};
`);

const mycircle = new Circle1(5,10);
mycircle.draw(); // 输出:drawing circle with radius 5

这里用转义符\确保内部的模板字符串语法被保留为代码的一部分,在draw函数调用时才执行插值。

额外说明

Function构造函数创建的函数运行在全局作用域,通常不推荐使用——它存在安全风险(若代码字符串来自不可信来源)且可读性差。更推荐使用普通构造函数或ES6类:

// 普通构造函数
function Circle(radius, centerX, centerY) {
  this.radius = radius;
  this.centerX = centerX;
  this.centerY = centerY;
  this.draw = function() {
    console.log(`drawing circle with radius ${this.radius}`);
  };
}

// ES6类
class Circle {
  constructor(radius, centerX, centerY) {
    this.radius = radius;
    this.centerX = centerX;
    this.centerY = centerY;
  }
  draw() {
    console.log(`drawing circle with radius ${this.radius}`);
  }
}

内容的提问来源于stack exchange,提问作者Engin Deniz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 10:34:50