gpt4 book ai didi

javascript - ES6 工厂模式 这是未定义的

转载 作者:行者123 更新时间:2023-12-03 09:11:49 24 4
gpt4 key购买 nike

我正在接触 ES6,并在 Javascript 中为实时项目实现设计模式。我有以下示例代码片段,它抛出一个错误,指出 this 关键字的计算结果为未定义:

export let LifecycleFactoryObj = (() => {
this.myCollection = new WeakSet();
//.... More here
this.add = function (opts) {
let tempObject = new MyCollection(opts);
this.myCollection.add(tempObject);
if (this.myCollection.has(tempObject)) {
return tempObject;
}
return null;
};
})();

抛出的错误是:

undefined.lifecycles = new WeakSet(); ^ TypeError: Cannot set property 'lifecycles' of undefined

看起来 IIFE 内的this被评估为未定义,但我似乎无法追踪原因。我认为在使用 let 进行变量实例化时,ES6 已经正确地确定了 this 关键字的范围。

谢谢!

最佳答案

如果您不使用构造函数或还没有对象,则

this 在 ES6 中不会定义;您需要使用传统语法 (function ClassName) 或新语法 (class ClassName) 来创建构造函数,然后调用该构造函数。

就您而言,似乎不需要完整的类,因此请尝试使用普通对象:

export let LifecycleFactoryObj = {
myCollection: new WeakSet(),
//.... More here
add: function(opts) {
let tempObject = new MyCollection(opts);
this.myCollection.add(tempObject);
if (this.myCollection.has(tempObject)) {
return tempObject;
}
return null;
}
};

关于javascript - ES6 工厂模式 这是未定义的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32057772/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com