【问题标题】:creating object foe the arrow function [duplicate]为箭头函数创建对象[重复]
【发布时间】:2020-08-13 08:07:54
【问题描述】:

场景(一)

var jk = function(name,age,lastanme){
    this.name = name;
    this.age = age;
    this.lastanme = lastanme; 

}

var op = new jk("ravi",45,"kumar");
console.log(op);

场景(二)

var jk = (name,age,lastanme)=>{
    this.name = name;
    this.age = age;
    this.lastanme = lastanme; 

}

var op = new jk("santhosh",45,"kumar");
console.log(op);

*const op = new jk("sandy",56,"kumar"); ^

TypeError: jk is not a constructor

为什么带有箭头函数的第二个程序会给出错误“jk 不是构造函数”?

【问题讨论】:

    标签: javascript json angular object inheritance


    【解决方案1】:

    每当我遇到困难时,我都会尝试查看文档,对于 javascript,您可以使用 mozilla mdn web docs

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

    你正在尝试做的是使用箭头函数作为构造函数,在文档中他们清楚地说明了

    Arrow functions cannot be used as constructors and will throw an error when used with new.

    所以,你想要的是

    var jk = (name,age,lastanme)=>{
        this.name = name;
        this.age = age;
        this.lastanme = lastanme; 
    
    }
    
    var op = jk("santhosh",45,"kumar");
    console.log(op);
    

    【讨论】:

      【解决方案2】:

      new 关键字用于创建类的对象实例。在 Javascript 中,它返回纯 Javascript 对象。它不能与箭头函数一起使用。

      在这种情况下,您应该直接调用该函数。试试下面的

      var op = jk("santhosh",45,"kumar");
      

      【讨论】:

        猜你喜欢
        • 2019-09-27
        • 1970-01-01
        • 2018-02-07
        • 2017-06-25
        • 2018-07-05
        • 2016-03-25
        • 1970-01-01
        • 2021-03-29
        • 2020-02-20
        相关资源
        最近更新 更多