5

What is the difference between the following two JavaScript functions? I know variables declared with var are local inside the function, and if declared withthis` keyword are exposed to outer word. is there any other difference between

function student(param1, param2, param3) {
    this.name = param1;
    this.age = param2;
    this.address = param3;
}

and

function student(param1, param2, param3) {
    var name = param1;
    var age = param2;
    var address = param3;
}
clearlight
  • 10,772
  • 11
  • 48
  • 65
Suraj
  • 1,437
  • 1
  • 11
  • 31
  • 3
    the first would be used to define an object you instantiate using the `new` keyword ... the second is a function that duplicates it's parameters in locally scoped vars – Jaromanda X Jan 15 '17 at 05:58
  • That is not at all what `this` does. You might want to read [this question](http://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work). – Dan Lowe Jan 15 '17 at 05:59
  • There is nothing more, except that if you call the function with the "new" keyword, "this" will refer to the new object. Try : `var s = new student("Anders", 22, "Norway"); console.log(s);`. – leaf Jan 15 '17 at 06:08

4 Answers4

3

Short answer: You would use the first one for a constructor. The second function does nothing. If you want to use 'private variables', refer to functional scoped variables in the contstructor by instance methods via a closure.

This function would be used the following way to create a student. The parameters passed in are assigned to the newly create student object.

 function student(param1, param2, param3){
  this.name = param1;
  this.age = param2;
  this.address = param3;
 }
 
 var student1 = new student('steve', 22,'333 E 3rd Ave');
 var student2 = new student('rachel', 34,'111 N 1st St');

 console.log(student1.name); // 'steve'
 console.log(student2.name); // 'rachel'

The second one wouldn't satisfy for a constructor.

It declares variables with functional scope that remain unused. Once the execution of the student function ends, the 3 variables defined within will be garbage collected. This function doesnt seem to accomplish anything.

What do you expect this function to do? It can't be used the same way:

 function student(param1, param2, param3){
  var name = param1;
  var age = param2;
  var address = param3;
 }

 var badStudent = new student('Greg', 22,'222 W 2nd Rd');
 
 console.log(badStudent.name); // undefined

Edit

Someone brought up how to make 'private member variables' using variables declared with var inside a constructor. Use closures:

function student(param1, param2, param3) {
  var name = param1;
  var age = param2;
  var address = param3;
  
  this.getName = function(newName) {
  
   if (newName)
    name = newName;
  
   return name;
  };
 }

 var myStudent = new student('steve', 22,'333 E 3rd Ave');

 console.log(myStudent.name);

 console.log(myStudent.getName());

 console.log(myStudent.getName('dan'));

 console.log(myStudent.getName());

Note that because the instance method getName refers to a functional scoped variable declared in the constructor, a closure remains that has references those variables. Because of the closure there are still references to the variables once the constructor ends, and they are not garbage collected. Thus via the instance method, you can get and set this variable which cannot be accessed via the resulting object of the constructor.

GantTheWanderer
  • 1,166
  • 1
  • 8
  • 19
1

Basic difference between this. vs var variables is the scope. Variables declared as a part of this will be part of objects and variables declared with var might be private. Might because, it depends on your return. If you do not use return, then they will be private

Sample

function Student(fname, lname, dob) {
  var _fname = fname, 
      _lname = lname,
      _dob = new Date(dob);
  
  this.fullName = _fname + " " + _lname;
  this.age = (new Date()).getFullYear() - _dob.getFullYear();
}

var stu = new Student('foo', 'bar', '1998/11/13');
console.log(stu);
console.log(stu._fname)

As you see, _fname is passed and was stored using var. So its scope is till function only. So when you try to access it outside function, it is not available.

So in simple, you can use this to define public properties and use var to define private ones.

Community
  • 1
  • 1
Rajesh
  • 21,405
  • 5
  • 35
  • 66
1

In JavaScript for creating object we use 'function' as constructor, this constructor functions basically return an object . when you declare variable with 'var' instants of 'this.var name' , in this case mean you try using those variable to create an object .those variable declared with 'var' just are local variable inside function.

on other hand , when you use 'this.variableName' you create a property for object that constructor function try to create it .

'this.' refer to object that constructor function create. 'var variableName' is just a local variable and it is not a property of 'this' object.

function student(param1,param2,param3){
this.name=param1;
this.age=param2;
this.address=param3;
}

var t=new student('farhad',28,'address');

will create this object:

t{
   name:'farhad',
   age:28,
   address:'address'
}

and

function student2(param1,param2,param3){
    var name=param1;
    var age=param2;
    var address=param3;
    }
var t2=new student2('farhad',28,'address');

will create this object:

t2{

}

in 't2' you don't see any property

0

this is used inside a function and it contains the value of the object that invokes function

Here this refers to the instance of the object & is not assigned a value until an object invokes the function where it is defined

function Student(param1, param2, param3) {
      this.name = param1;
      this.age = param2;
      this.address = param3;
      this.print = function() {
        console.log(this.name + this.age + this.address)
      }
    }
    var stud = new Student('a', 'b', 'c');
    stud.print(); // abc

In the later case var name=param1;var age=param2;var address=param3; you are assigning each of the parameters to a variable and this variables have scope only inside the function

brk
  • 43,022
  • 4
  • 37
  • 61
  • 1
    Oops, "*…it contains the value of the object that invokes function*" is incorrect. *this* can be set to any object, or any value in strict mode. It's set by the call or *bind*, or lexically for arrow functions. Calling a method of an object is just one way to set *this*, it's also set using *call*, *apply*, *bind*, *new*, etc. – RobG Jan 15 '17 at 06:35