0

Can somebody explain the difference?

function Constr(name){
this.firstname=name;
this.log=function(){
console.log(this.firstname);}
}

And

function Constr(name){
this.firstname=name;
this.log=function(){
console.log(name);}
}

Is there a difference using the property or the argument?

Many Thankd

Greetings KAT

Kat
  • 61
  • 3
  • Aside your question, you should throw your books to the trashes, and get something written after 2015. It's very exceptional to create a constructor function in modern JS, because we've had [Classes](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes) since ES6, the current version is ES13. – Teemu Jan 10 '23 at 07:07

1 Answers1

0

The local variable (constructor parameter) cannot be changed from outside. The property value can.

const obj = new Constr("a");
obj.log();
obj.firstname = "b";
obj.log();

Compare how the two versions behave differently in the above snippet. Btw, you also should avoid creating methods in the constructor but rather define them on the the prototype, which makes it impossible for them to access local variables from the constructor scope. See also Javascript: Do I need to put this.var for every variable in an object?.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375