Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to understand scoping within two short JavaScript functions

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;
}
like image 554
Suraj Avatar asked Jan 15 '17 05:01

Suraj


1 Answers

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.

like image 83
GantTheWanderer Avatar answered Sep 30 '22 04:09

GantTheWanderer