你应该使用这个。参考工厂函数中的 属性?

Should you use this. in reference to a property in factory functions?

各位,我正在努力思考工厂功能。我想知道制作接受参数的工厂函数的正确方法是什么。

我们赋予它创建的对象的方法是不是应该通过this来引用它的属性。在他们前面?

例如:

//using this. 
function createPerson(name) {
    return {
        name,
        talk() {
            console.log(this.name);
        }
    }
}

或者这样:

//not using this. 
function createPerson(name) {
    return {
        name,
        talk() {
            console.log(name);
        }
    }
}

我都试过了,它们的表现似乎都一样,我想我可能错了。意思是如果我 运行 以下内容:

const marc = createPerson('marc');
const joe = createPerson('joe');
marc.talk();
joe.talk();

在这两种情况下我得到相同的输出,所以有必要使用它吗?在工厂功能中?通常的做法是什么?谢谢你帮助我

您的用例使用 this 只是因为返回的对象具有 name 属性.

this的上下文是返回对象而不是createPerson函数对象

如果您在对象外部有一个变量并尝试使用 this 访问它,它将不起作用。

this 的上下文可能很复杂,我认为您知道用例中的 this 是什么很容易感到困惑

//not using this. 
function createPerson(name) {
    // without using new createPerson() "this" is not the function object
    const upper = this.upper = name.toUpperCase();

    return {
        name,
        talk() {
            console.log('this.upper', this.upper)
            console.log('upper', upper);
        }
    }
}

const foo= createPerson('foo')
foo.talk()