1

I am trying to build(or return) javascript object using two different patterns 1. factory pattern 2. constructor pattern

Here is the code using factory pattern

function employee(){
    var emp = {
        firstName : 'mihir',
        lastName : 'hapaliya',
        that : this
        }
    return emp;
}

console.log(employee().that);

Here is the code using constructor pattern

function employee(){
    this.firstName = '';
    this.lastName = '';
    this.that = this;
}

console.log(new employee().that);

Both pattern return employee object. I have variable 'that' to which i am assigning the scope of this variable

scope of this variable is employee object in constructor pattern(expected behavior).

Why scope of this variable is window in factory pattern thought it is property of emp of object?

So both pattern building the same javascript(employee) object but the way of creating object is different then why the scope of this variable is different?

mihir hapaliya
  • 211
  • 2
  • 8
  • In loose mode, when you call a function the way you're calling `example` in your factory example (`employee()`), `this` is set to refer to the global object (`window`, on browsers) during the call. When you use `new` with a constructor function (your second approach), `new` creates a new object and sets `this` to refer to it during the call. See the linked question's answers for more. – T.J. Crowder Sep 09 '17 at 13:50
  • Note: `this` and "scope" have nearly nothing to do with one another. `this` is not scope. `this` is just a pseudo-variable that's set automatically in various ways depending on how you call a function, or manually if you use [`call`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call) or `apply`. The **only** thing `this` and scope have to do with one another is that a specific execution of a scope (called an *execution context*) has a *fixed* value for `this` (or none, with arrow functions, meaning the context inherits it from its parent context). – T.J. Crowder Sep 09 '17 at 13:52
  • thank you for your reply. but still i have a doubt. I couldn't find the proper answer from the link.....object literal {} and new keyword both creates the object then how the value of 'this' is different ?....appreciate if you can explain in depth... – mihir hapaliya Sep 09 '17 at 19:48
  • The answers to the linked question *do* explain it in depth. Creating objects has virtually nothing to do with `this`. Other than the global `this`, `this` is determined by how you call a function (and what kind of function it is). – T.J. Crowder Sep 10 '17 at 08:11

0 Answers0