0

I do a classical JavaScript object initialization like this, it works like a charm:

function Hero(a, n) {                                                            
    this.nom = a;                                                                
    this.job = n;                                                                
    this.quiSuisJe = function() {
        return "Mon nom est "+this.nom+" et je suis un "+this.job;
    } 
}                                                                                
var x = new Hero("Joe", "Ninja");                                                
var y = new Hero("Jinx", "Carry AD");                                            
console.log(x.quiSuisJe());                                                      
console.log(y.quiSuisJe()); 

But if I change the quiSuisJe function like this:

function Hero(a, n) {                                                            
    this.nom = a;                                                                
    this.job = n;                                                                
    this.quiSuisJe = function() {
        return "Mon nom est "+a+" et je suis un "+n;
    } 
}                                                                                
var x = new Hero("Joe", "Ninja");                                                
var y = new Hero("Jinx", "Carry AD");                                            
console.log(x.quiSuisJe());                                                      
console.log(y.quiSuisJe()); 

It works. Why?

Olivier Pons
  • 15,363
  • 26
  • 117
  • 213
  • 5
    Closure. The inner function is closure, it has access to the parent function vars. Also note that the inner function is created for each instance. – Tushar Feb 24 '16 at 14:41
  • 2
    Now try `x.nom = "qwerty"; x. quiSuisJe();` in both and see what happens. – epascarello Feb 24 '16 at 14:47

1 Answers1

0

A constructor is still a function, so since you've declared a function within it, you essentially create a closure. This means that inside this new function you have access to properties of top-level function. Of course, just because you DO have access to it, doesn't mean you should use it like this. Try to use this instead, like you have in your first example.

GMchris
  • 5,439
  • 4
  • 22
  • 40
  • Thank you very much for you answer, but I still dont know why those variables are not destroyed. I understand why dynamic declared variable are not destroyed (why they can't) if they are used within a following "inner" function (variable scoping), but the problem here is that they are **not** declared like `var a ="blabla", b="blibli";` but they are *parameters*... I think I'm missing something. – Olivier Pons Feb 24 '16 at 14:51
  • You can pretty much consider parameters to be `var a= 'blabla'` placed at the very top of the function. – GMchris Feb 24 '16 at 14:55