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.
Should the methods we give the objects that it creates refer to its properties by using 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. in the factory 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.
The context of this
is the returned object and not the createPerson function object
If you were to have a variable outside the object and try to access it with this
it won't work.
The context of this
can be compicated and I think that you can easily get confused knowing what this
is in your use case
//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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.