ES6 工厂模式这是未定义的
ES6 Factory Pattern this is undefined
我正在接触 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 被评估为 undefined 但我似乎无法追踪原因。我认为 ES6 在使用 let 进行变量实例化时正确地确定了 this 关键字的范围。
谢谢!
this
如果您不使用构造函数或还没有对象,则在 ES6 中未定义;您需要使用传统语法 (function ClassName
) 或新语法 (class ClassName
) 创建构造函数,然后调用该构造函数。
在你的情况下,似乎不需要完整的 class,所以尝试使用普通对象:
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;
}
};
我正在接触 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 被评估为 undefined 但我似乎无法追踪原因。我认为 ES6 在使用 let 进行变量实例化时正确地确定了 this 关键字的范围。
谢谢!
this
如果您不使用构造函数或还没有对象,则在 ES6 中未定义;您需要使用传统语法 (function ClassName
) 或新语法 (class ClassName
) 创建构造函数,然后调用该构造函数。
在你的情况下,似乎不需要完整的 class,所以尝试使用普通对象:
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;
}
};