如何在JavaScript内置Function构造函数中接收两个参数
解决Function构造函数接收多参数的问题
我来帮你排查一下问题所在,你遇到的情况主要是两个细节没处理对:参数传递的规范,以及构造函数内部属性的绑定方式。
首先看你最初的代码,函数体里的password = upass没有绑定到this上,这会导致this.password始终是undefined,调用print方法自然拿不到正确的值。另外你尝试的两种参数写法本身是有效的,但因为函数体的赋值逻辑错误才导致失效。
下面是修正后的正确实现:
写法1:参数作为独立字符串传递
let account = new Function('uname', 'upass', ` this.username = uname; this.password = upass; // 关键:把属性绑定到实例的this上 this.print = function() { console.log(this.username, this.password); }; `); let LoginAct = new account('deva', 'deva'); LoginAct.print(); // 输出:deva deva
写法2:参数作为逗号分隔的单个字符串传递
let account = new Function('uname, upass', ` this.username = uname; this.password = upass; // 同样要绑定到实例this this.print = function() { console.log(this.username, this.password); }; `); let LoginAct = new account('deva', 'deva'); LoginAct.print(); // 输出:deva deva
关键注意事项:
- 构造函数内部必须把属性赋值给
this,否则属性会变成全局变量(非严格模式下),而不是当前实例的专属属性。 - 使用
Function构造函数时,参数字符串里的空格不影响解析,但尽量保持规范,比如'uname,upass'或者'uname', 'upass'都是可行的。 - 你最初的代码里只传了
'uname '作为参数,第二个参数直接是函数体,导致upass根本没被当作参数传入,这也是之前无效的核心原因之一。
内容的提问来源于stack exchange,提问作者DevashishBhor
相关产品推荐
相关产品推荐

