stefan22
10/21/2017 - 2:16 AM

1 - example of a closure . 2. - closure that returns an object. Fn say is private inside of person and you can access it with greetin

1 - example of a closure .

    • closure that returns an object. Fn say is private inside of person and you can access it with greeting .
    • two functions inside of one called person withoout args. Get a handle cause it's not an instance and access it using dot notation .
// example 1        //one has an arg and two also has one
function one(x) {
  
    function two(y) {
        console.log( x + y );
    }
  
    return two;
  
} //one

//first
var first = one(5);
//second
var second = first(10);   //remembers the five from before or the whatever the x value

//returns 15


// example 2 closure returning object

function person(name) {     //only name arg is passed

	function say() {          //no arg here
		console.log('hello ' + name);
	}//say

	return {
		greeting:say
	};

}//person

var mark = person('Mark');

mark.greeting();

//returns hello Mark


// example 3    //person no arg and obj notation to grab first and last
function person() {

	function firstName(first) {
		console.log('first name is: ' + first);
	}//say

	function lastName(last) {
		console.log('last name is: ' + last);
	}

	return {
		firstName: firstName,
    lastName: lastName
	};

}//person

var guyOne = person();
//firstname
guyOne.firstName('John');  //returns first name is John
//lastname
guyOne.lastName('Morris');  //return last name is Morris