Why not using 'this' in factory functions doesn't raise an error?

Hello, I’m new to forum so if there is any similar topic with mine. Sorry but I couldn’t find it. My question is when i create factory function with using this in my fullName method it works good. But whenever I delete this key it still works, why?

function myfactory(name,lastname) {
  return {
    get fullName() {
      return name + " " + lastname;
const fudayl = myfactory('fudayl','cavus')
console.log(fudayl.fullName) // fudayl cavus
const test = myfactory('Name','LastName')
console.log(test.fullName) // Name LastName

Give undefined when I ran your code:

JS Bin - Collaborative JavaScript Debugging

(press run, top right corner). I think you might have ran into a caching issue. this provides the necessary contextual binding and must be used

I’m sorry, it because of method name in the console.log. I fixed it.

I would still use this keyword, is more explicit.

JavaScript is full of quirks and caveats. I don’t know this one. Personally, I would avoid/stay clear of relying on such quirks, might lead to problems further down the road

Hello, and welcome to the forums!

It only appears to work but it isn’t actually using the value of name from the object:

test.name = 'Rumpelstiltskin';
console.log(test.fullName); // Name LastName

Even when updating the name property of the object, that getter will still return the original values. Had you used this.name and this.lastname, the getter would return what you expect.

If you’re interested in the how / why of what’s happening, you can read up on Closures

1 Like