-2

when I define "Car" like below,

var Car = function(m) {
    var model = m;
    function getModel() {
        return model;
    }
    return {
        getModel : getModel
    }
};

and I created an object like this var c1 = new Car("qwer");

in this case, I can't access to model directly, only by closure.

(console.log(c1.model); => undefined)

(console.log (c1.getModel ()); => qwer)

but when I define "Car" like below,

var Car = function(m) {
    var model = m;
    function getModel() {
        return this.model;
    }
    return {
        getModel : getModel
    }
};

and I created object var c2 = new Car("asdg");

in this case, I can not access to model directly , but also by closure.

(console.log(c2.model)  =>  undefined)

(console.log (c2.getModel () => undefined)

can u tell me why this happens?

Suraj Rao
  • 28,186
  • 10
  • 88
  • 94
Jihwan Kim
  • 31
  • 1
  • 5
  • Because `this` refers to the instance and there is no `model` instance variable...? `model` is a *local variable*, essentially private and not on the instance. Also, returning from a constructor does nothing... the return statement is ignored because constructors aren't supposed to return anything. – Andrew Li May 25 '17 at 06:37
  • 1
    I'm sure there's a post somewhere that explains `this` – Jaromanda X May 25 '17 at 06:37
  • [here's one](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work/3127440#3127440) – Reyno May 25 '17 at 06:43
  • That _model_ is a local variable, it is not a property of the object created. – Jai May 25 '17 at 06:43

1 Answers1

1

In first case when you do:

(console.log (c1.getModel ()); => qwer)

You get "qwer" because getModel() function can read variable model from outer scope.

However, in second case, in the line return this.model;, this is dynamically bound to c2 object and c2 object doesn't have model. All c2 has is the function getModel(). You can achieve the desired result in the following way:

var Car = function(m) {
  this.model = m;
  this.getModel = function() {
    return this.model;
  }
  //return {
  //    getModel: getModel
  //}
};
var c2 = new Car("asdg");
console.log(c2.getModel());

Note that even above solution is less than ideal because, functions should ideally be attached to constructor function's prototype object. So, I would suggest you do some looking around stack overflow a bit and you would get some more insight.

Pankaj Shukla
  • 2,435
  • 2
  • 9
  • 17