【问题标题】:How to accept two parameter in inbuilt constructor function in javascript如何在javascript的内置构造函数中接受两个参数
【发布时间】:2020-07-09 10:33:33
【问题描述】:

这里有我的代码

// creating objects using builtin construcor functions
let account = new Function ('uname ' , `this.username=uname;
                        username = uname;
                        password = upass;
                        this.print = function(){
                            console.log(this.username, this.password);
                        }`);
let LoginAct = new account('deva', 'deva');
LoginAct.print();

在这里,我使用内置函数 Function() 创建了一个名为 account 的构造函数。现在在这里我想接受对象的两个参数,其中第一个是 uname 而第二个是 uppass 。我试着写这样的东西:-let account = new Function ('uname ' , 'upass', `this.username=uname;...

还有这样的:- let account = new Function ('uname , upass', `this.username=uname;...

但它没有工作!请帮忙!

【问题讨论】:

    标签: javascript function object constructor


    【解决方案1】:

    您的第一次尝试 (new Function('param1', 'param2', 'function body')) 应该会成功。问题是您没有设置this.password。所以当你打电话给LoginAct.print()this.passwordundefined

    // creating objects using builtin construcor functions
    let account = new Function ('uname', 'upass', `
      this.username = uname;
      this.password = upass; // <- set this.password
      this.print = function() {
        console.log(this.username, this.password);
      }
    `);
    let LoginAct = new account('deva', 'deva');
    LoginAct.print();

    【讨论】:

    • 谢谢,我忘了指出那些变量。非常感谢。
    【解决方案2】:

    我想要这样的代码

    // creating objects using builtin construcor functions
    let Account = function(uname, upass) {
      this.username = uname;
      this.password = upass;
      this.print = function() {
        console.log(this.username, this.password);
      }
    };
    let loginAct = new Account('deva', 'deva');
    loginAct.print();

    【讨论】:

    • 我知道这个。但是多学一点没有坏处。毫无疑问,您建议的那个是最好的,但我也想学习。谁知道它可以在哪里帮助我。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-21
    • 2012-10-22
    • 2019-01-09
    • 1970-01-01
    • 2012-10-20
    • 1970-01-01
    相关资源
    最近更新 更多