Created
November 28, 2014 11:11
-
-
Save kkoziarski/1635568be13aad77d1d5 to your computer and use it in GitHub Desktop.
Closere - The Good Parts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Instead of initializing myObject with an object literal, we will initialize myObject by | |
//calling a function that returns an object literal. That function defines a value variable. That variable is always available to the increment and getValue methods, but | |
//the function’s scope keeps it hidden from the rest of the program. | |
//We are not assigning a function to myObject. We are assigning the result of invoking | |
//that function. Notice the()on the last line. The function returns an object containing two methods, and those methods continue to enjoy the privilege of access to the | |
//value variable. | |
var myObject = function ( ) { | |
var value = 0; | |
return { | |
increment: function (inc) { | |
value += typeof inc === 'number' ? inc : 1; | |
}, | |
getValue: function ( ) { | |
return value; | |
} | |
}; | |
}(); | |
// Create a maker function called 'quo'. It makes an | |
// object with a get_status method and a private | |
// status property. | |
var quo = function (status) { | |
return { | |
get_status: function ( ) { | |
return status; | |
}, | |
another_public_property: "xyz" | |
}; | |
}; | |
// Make an instance of quo. | |
var myQuo = quo("amazed"); | |
document.writeln(myQuo.get_status( )); | |
//This 'quo' function is designed to be used without the newprefix, so the name is not | |
//capitalized. When we call quo, it returns a new object containing a 'get_status' | |
//method. A reference to that object is stored in 'myQuo'. The 'get_status' method still | |
//has privileged access to quo’s 'status' property even though 'quo' has already returned. | |
//'get_status' does not have access to a copy of the parameter; it has access to the | |
//parameter itself. This is possible because the function has access to the context in | |
//which it was created. This is called 'closure'. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment