简体   繁体   English

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

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

everyone, i am trying to wrap my head around factory functions.大家,我正试图围绕工厂功能。 I want to know what is the proper way to make a factory function that takes in a parameter.我想知道制作一个接受参数的工厂 function 的正确方法是什么。

Should the methods we give the objects that it creates refer to its properties by using this.我们给它创建的对象的方法是否应该通过使用 this 来引用它的属性。 in front on them?在他们面前?

For example:例如:

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

or this way:或者这样:

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

I have tried both and they both seem to perform the same way, which I assume I am probably wrong about.我都尝试过,它们似乎都以相同的方式执行,我认为我可能错了。 Meaning if i run the following:意思是如果我运行以下命令:

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

in both cases I get the same output, so is it necessary to use this.在这两种情况下,我得到相同的 output,所以有必要使用它。 in the factory function?在工厂 function? What is the common practice?常见的做法是什么? thank you for helping me感谢你们对我的帮助

Your use case is working with this only because the returned object has that name property.您的用例正在使用this只是因为返回的 object 具有该name属性。

The context of this is the returned object and not the createPerson function object上下文是返回this object 而不是 createPerson function object

If you were to have a variable outside the object and try to access it with this it won't work.如果您要在 object 之外有一个变量并尝试使用this访问它,它将无法正常工作。

The context of this can be compicated and I think that you can easily get confused knowing what this is in your use case上下文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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM