【问题标题】:How to fix 'Not a constructor function' error in javascirpt如何修复javascript中的“不是构造函数”错误
【发布时间】:2019-04-22 16:44:38
【问题描述】:

我试图了解对象原型是如何工作的,因此尝试了“Javascript:The Good Parts”一书中的一段代码并得到了一个错误。

我只是为了好玩而修改了代码并得到了错误。如果运行原始代码,它会起作用并显示输出。

这是原始代码,没有任何错误。

let stooge = {
    'first-name': 'John',
    'last-name' : 'Peter'
};

if(typeof Object.create !== 'function') {
Object.create = (o) => {
    let F = () => {};
    F.prototype = o;
    return new F();
};
}

let theOtherStooge = Object.create(stooge);
console.log(theOtherStooge['first-name'], theOtherStooge['last-name']);

我删除了 if 条件并得到一个错误,说 F 不是构造函数。有人可以解释一下为什么会这样吗?请原谅,我是编程初学者。

修改后的代码:

let stooge = {
    'first-name': 'John',
    'last-name' : 'Peter'
};

Object.create = (o) => {
let F = () => {};
    F.prototype = o;
    return new F();
};

let theOtherStooge = Object.create(stooge);
console.log(theOtherStooge['first-name'], theOtherStooge['last-name']);

【问题讨论】:

    标签: javascript-objects


    【解决方案1】:

    至少在 Chrome 中Object.create 已经定义为函数,因此第一个示例的if 语句中的代码都没有运行。如果没有if 语句,则会运行引发异常的代码。错误的原因是分配给F 的lambda 函数不被视为构造函数。基于this answer,问题在于this对象在创建时被分配给围绕lambda函数的范围,而this被分配给对象调用 使用常规函数时的函数。您可以更改代码以使用常规函数:

    let stooge = {
      'first-name': 'John',
      'last-name': 'Peter'
    };
    
    Object.create = (o) => {
      let F = function() {};
      F.prototype = o;
      return new F();
    };
    
    let theOtherStooge = Object.create(stooge);
    console.log(theOtherStooge['first-name'], theOtherStooge['last-name']);

    【讨论】:

    • 谢谢。是的,箭头函数不能用作构造函数。
    猜你喜欢
    • 2019-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-10
    • 1970-01-01
    • 2019-10-22
    • 2013-09-26
    • 1970-01-01
    相关资源
    最近更新 更多