Advertisement
Guest User

Untitled

a guest
Jul 23rd, 2017
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 21.12 KB | None | 0 0
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta name="function,scope,closure" content="[function,scope,closure]">
  5. <meta charset="utf-8">
  6. <meta name="viewport" content="width=device-width">
  7. <title>JS Bin</title>
  8. </head>
  9. <body>
  10.  
  11. <script id="jsbin-javascript">
  12.  
  13. //Functions
  14. /*Functions
  15. Functions allow us to encapsulate a block of code, and execute that block of code whenever we want and how ever many times we want.
  16.  
  17. Where Numbers are numeric data, and Strings are character data, you can think of a Function as logic data.
  18.  
  19. Like a recipe is a set of instructions, so Functions are a list of instructions. Functions encapsulate a block of code. You can pass around this block of code in your program, and execute the instructions at some later point.
  20.  
  21. Two phases of using Functions
  22. declaration/definition: creating the Function.
  23. invocation/calling/executing/applying: using the Function.
  24.  
  25.  
  26. Function Definitions
  27. Before you can use your Function, you must first define your Function. This is simply the process of designing some code you want to execute when your Function is called.
  28. */
  29.  
  30. //The keyword to declare a Function is, function.
  31.  
  32. function(parameterOne, parameterTwo) {
  33. // function body: code goes here, NOTE indentation!
  34. }
  35.  
  36. /*Inputs/Output
  37. When designing Functions, we can list any number of required inputs. We call these inputs parameters, and we list them between the parenthesis, like so:
  38. */
  39. function(numOne, numTwo) {} // function body code... }
  40.  
  41. //The above Function takes two parameters, numOne, numTwo. You should always strive to name your parameters so it’s crystal clear what needs to be provied when executing the Function. In the above example, it’s clear we should pass in two Number values.
  42.  
  43. //Functions return a single output. By default, Functions will return undefined.
  44.  
  45. console.log((function() {}())); // prints undefined
  46.  
  47. //Otherwise, we can explicitly return value by using the return keyword followed by a value.
  48.  
  49. function(numOne, numTwo) {
  50. return numOne + numTwo;
  51. }
  52.  
  53. /*Named Functions, Anonymous Functions, & Function Expressions
  54. Functions can be named, or assigned to variables or constants, or anonymous.
  55.  
  56. Named Functions
  57. A named Function looks like this:
  58. */
  59. function add(numOne, numTwo) {
  60. return numOne + numTwo;
  61. }
  62. /*
  63. Above, the name of the Function is add. Named Function definitions are hoisted to the top of their scope, so they can be used in the program before they appear to be sequentially defined.
  64. */
  65. const sum = add(1, 1); // add is called before it appears to be defined.
  66.  
  67. console.log(sum); // prints 2
  68. function add(numOne, numTwo) {
  69. return numOne + numTwo;
  70. }
  71. /*To understand hoisting, be aware that before JavaScript begins to execute code in a script, it first sweeps the scope in which it’s executing, either the global scope or the scope of a Function being executed, and hoists into memory named Function definitions and any variables. This means named Functions can be called before they appear to be defined.
  72.  
  73. In the above example, the named Function add() is called before its definition appears sequentially in the code.
  74.  
  75. Anonymous Functions
  76. Many of the above examples are anonymous Functions, meaning, they’re defined without a name. Anonymous Functions are typically written while being passed to other Functions, like so:
  77. */
  78. function printAlteredString(string, alterString) {
  79. console.log(alterString(string));
  80. }
  81. printAlteredString('hello', function(str) { return str.toUpperCase(); }); // prints 'HELLO';
  82.  
  83. /*In the above example, the anonymous Function is defined on the fly as an argument being passed to the Function, printAlteredString(). The anonymous Function gets plugged into the parameter, alterString, which is then executed and passed to console.log().
  84.  
  85. The fact that we can pass Function definitions as values to other Functions is an exmaple of Functions in JavaScript being first class Objects. This feature provides a great deal of flexibility when writing code. Above, while defining the Function printAlteredString(), we’re not committing to how we’re altering the String. How we alter the String will happen later, when we call printAlteredString()!
  86.  
  87. Function Expressions
  88. A Function expression is formed when an anonymous Function is assigned to a variable or constant.
  89. */
  90. const sum = add(1, 1); // Throws an Error: TypeError: add is not a function
  91. const add = function(numOne, numTwo) {
  92. return numOne + numTwo;
  93. //};
  94. /*
  95. Above, trying to call add() before it’s assigned will throw an error. The reason for this should be clear - the constant add is yet to be assigned!
  96.  
  97. When using the pattern of Function expressions, you can only call the Function after it’s been assigned to a variable or constant:
  98. */
  99. //const add = function(numOne, numTwo) {
  100. return numOne + numTwo;
  101. //};
  102. const sum = add(1, 1);
  103. console.log(sum); // prints 2, no error...
  104. /*The fact that we can assign Function definitions to a variable or constant is another exmaple of Functions in JavaScript being first class Objects.
  105.  
  106. Calling a Function
  107. To use a Function, we have to call it. Calling a Function will run the code within the body or code block of the Function. Executing, invoking, applying, running are all synonymous with calling a Function.
  108.  
  109. Arguments
  110. Arguments (inputs) are what we call the values passed to a Function when we execute the Function. You can think of arguments like passengers, and paramters like car seats.
  111.  
  112. If we defined a Function with two parameters, thats two car-seats. When we call that Function, we’ll pass in two values, that’s two passengers, one for each car-seat.
  113.  
  114. To call a Function, you must reference its name or the variable name to which its assigned, then pass any values expected.
  115. */
  116. const add = function(numOne, numTwo) {
  117. return numOne + numTwo;
  118. };
  119. const sum = add(1, 1);
  120. console.log(sum); // prints 2
  121. /*We can assign the result of a Function to a variable or constant, like we did in the above example. The result of add(1, 1) was assigned to the constant, sum.
  122.  
  123. Or, we can pass the invocation as a value to another Function as input:
  124. */
  125. const add = function(numOne, numTwo) {
  126. return numOne + numTwo;
  127. };
  128. console.log(add(1, 1)); // prints 2
  129. //In this regard, all Functions are expressions, because they produce a value!
  130.  
  131.  
  132. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  133.  
  134. //Constructor function
  135. //A Constructor Function is a Function invoked to CREATE an INSTANCE of a particular type of value.
  136.  
  137. var car1={
  138. color:'blue',
  139. transmission:'auto',
  140. make:'honda',
  141. horsepower:'90'
  142. }
  143.  
  144. var car2={
  145. color:'red',
  146. transmission:'auto',
  147. make:'yoda',
  148. horsepower:'120'
  149. }
  150.  
  151. //...et. or use the constructor function
  152.  
  153. var Car=function(color,transmission,make,horsepower){
  154. this.color=color;
  155. this.transmission=transmission;
  156. this.make=make;
  157. this.horsepower=horsepower;
  158. }
  159.  
  160. var myCar=new Car('red','manual','yoda',280);
  161. console.log(myCar);
  162. var yourCar=new Car('red', 'auto','ooda',220);
  163. console.log(yourCar);
  164. var ourCar=new Car('blue','auto','yoda',160);
  165. console.log(ourCar);
  166.  
  167.  
  168. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  169.  
  170.  
  171. //scope
  172. Scope
  173. Scope refers to what variables or constants are accessible, where.
  174.  
  175. There are basically two types of scope: Global scope and local.
  176. Global scope is anything outside of Function, and local scopes are local to a Function body.
  177.  
  178. Generally, Functions enclose a scope and protect their variables from parent scopes, including the global scope.
  179.  
  180. Functions can access the variables in their parent scopes! But parent scope cannot access variables in child scopes.
  181.  
  182. //Global Scope
  183. // Here, a is in the global scope, and is visible within the scope of doSomething() //
  184. let a = 1;
  185. function doSomething() {
  186. a = 2;
  187. }
  188. console.log(a); // prints 1
  189. doSomething();
  190. console.log(a); // prints 2
  191.  
  192. In the above example, a is accessible within the body or scope of doSomething(), and can therefore alter the value a contains.
  193.  
  194. In the example below, the variable person is created within the scope of the Function doSomething(), so it is not accessible in the parent scope.
  195.  
  196.  
  197. Function Scope or Local Scope
  198. Local scope refers to declarations that happen within the body of a Function. These declarations are only available within the Function itself and any Functions declared within it.
  199.  
  200. function doSomething() {
  201. var a = 1;
  202. console.log(a);
  203. }
  204. console.log(a); // => throws ReferenceError: a is not defined
  205.  
  206. //Nested Scope
  207. Function can be defined within other Functions, forming nested scopes. In the following example, a is decalred within doSomething(), but is accessible within the child scope of doSomethingElse()!
  208.  
  209. function doSomething() {
  210. let a = 1;
  211. function doSomethingAgain() {
  212. a = 2;
  213. }
  214. doSomethingAgain();
  215. console.log(a); // prints 2
  216. }
  217. doSomething();
  218. But parent scopes do not have access to declarations within children scopes:
  219.  
  220. function doSomething() {
  221. function doSomethingAgain() {
  222. var a = 1;
  223. }
  224. doSomethingAgain();
  225. console.log(a); // => throws ReferenceError: a is not defined
  226. }
  227. doSomething();
  228.  
  229. Function scopes allow us to create privacy - declarations that are not accessible in to other parts of our applcation.
  230.  
  231. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~```
  232.  
  233. Closure
  234. Maintaining access to values by enclosing them in Function bodies
  235.  
  236. Closure
  237. Simply put, a Function definition can carry within its body references to variables in its parent scope. This term is called closure. The Function definition forms a closure around the environment in which it was defined. This means the invocation of the Function has access to variables of its parent scope.
  238.  
  239. function makePerson(nameFirst, nameLast) {
  240. var friends = [];
  241.  
  242. return {
  243. nameFirst: nameFirst,
  244. nameLast: nameLast,
  245. addFriends: function() {
  246. Array.prototype.push.apply(friends, Array.prototype.slice.call(arguments));
  247. },
  248. getNumFriends: function() {
  249. return friends.length;
  250. },
  251. getFriendNames: function() {
  252. return friends.map(function(friend){
  253. return friend.nameFirst + ' ' + friend.nameLast;
  254. })
  255. .join(", ");
  256. }
  257. };
  258. }
  259. Above, when invoking makePerson(), the inner Function definitions of addFriends(), getNumFriends(), getFriendNames() form closures that carry with them a reference to the Array stored in the friends variable.
  260.  
  261. Below, because we keep the person-Object returned from the call to makePerson() in a variable, for example, john, we’ve created a private member. The friends Array is available only through the API of the person-Object. Client code does not have direct access to the friends Array, but as you can see below, it is ALIVE!
  262.  
  263. var john = makePerson('John', 'Fraboni');
  264. var alice = makePerson('Alice', 'Green');
  265. var greg = makePerson('Greg', 'Bara');
  266. john.addFriends(greg, alice);
  267. console.log(john.getFriendNames());
  268. </script>
  269.  
  270.  
  271.  
  272. <script id="jsbin-source-javascript" type="text/javascript">
  273. //Functions
  274. /*Functions
  275. Functions allow us to encapsulate a block of code, and execute that block of code whenever we want and how ever many times we want.
  276.  
  277. Where Numbers are numeric data, and Strings are character data, you can think of a Function as logic data.
  278.  
  279. Like a recipe is a set of instructions, so Functions are a list of instructions. Functions encapsulate a block of code. You can pass around this block of code in your program, and execute the instructions at some later point.
  280.  
  281. Two phases of using Functions
  282. declaration/definition: creating the Function.
  283. invocation/calling/executing/applying: using the Function.
  284.  
  285.  
  286. Function Definitions
  287. Before you can use your Function, you must first define your Function. This is simply the process of designing some code you want to execute when your Function is called.
  288. */
  289.  
  290. //The keyword to declare a Function is, function.
  291.  
  292. function(parameterOne, parameterTwo) {
  293. // function body: code goes here, NOTE indentation!
  294. }
  295.  
  296. /*Inputs/Output
  297. When designing Functions, we can list any number of required inputs. We call these inputs parameters, and we list them between the parenthesis, like so:
  298. */
  299. function(numOne, numTwo) {} // function body code... }
  300.  
  301. //The above Function takes two parameters, numOne, numTwo. You should always strive to name your parameters so it’s crystal clear what needs to be provied when executing the Function. In the above example, it’s clear we should pass in two Number values.
  302.  
  303. //Functions return a single output. By default, Functions will return undefined.
  304.  
  305. console.log((function() {}())); // prints undefined
  306.  
  307. //Otherwise, we can explicitly return value by using the return keyword followed by a value.
  308.  
  309. function(numOne, numTwo) {
  310. return numOne + numTwo;
  311. }
  312.  
  313. /*Named Functions, Anonymous Functions, & Function Expressions
  314. Functions can be named, or assigned to variables or constants, or anonymous.
  315.  
  316. Named Functions
  317. A named Function looks like this:
  318. */
  319. function add(numOne, numTwo) {
  320. return numOne + numTwo;
  321. }
  322. /*
  323. Above, the name of the Function is add. Named Function definitions are hoisted to the top of their scope, so they can be used in the program before they appear to be sequentially defined.
  324. */
  325. const sum = add(1, 1); // add is called before it appears to be defined.
  326.  
  327. console.log(sum); // prints 2
  328. function add(numOne, numTwo) {
  329. return numOne + numTwo;
  330. }
  331. /*To understand hoisting, be aware that before JavaScript begins to execute code in a script, it first sweeps the scope in which it’s executing, either the global scope or the scope of a Function being executed, and hoists into memory named Function definitions and any variables. This means named Functions can be called before they appear to be defined.
  332.  
  333. In the above example, the named Function add() is called before its definition appears sequentially in the code.
  334.  
  335. Anonymous Functions
  336. Many of the above examples are anonymous Functions, meaning, they’re defined without a name. Anonymous Functions are typically written while being passed to other Functions, like so:
  337. */
  338. function printAlteredString(string, alterString) {
  339. console.log(alterString(string));
  340. }
  341. printAlteredString('hello', function(str) { return str.toUpperCase(); }); // prints 'HELLO';
  342.  
  343. /*In the above example, the anonymous Function is defined on the fly as an argument being passed to the Function, printAlteredString(). The anonymous Function gets plugged into the parameter, alterString, which is then executed and passed to console.log().
  344.  
  345. The fact that we can pass Function definitions as values to other Functions is an exmaple of Functions in JavaScript being first class Objects. This feature provides a great deal of flexibility when writing code. Above, while defining the Function printAlteredString(), we’re not committing to how we’re altering the String. How we alter the String will happen later, when we call printAlteredString()!
  346.  
  347. Function Expressions
  348. A Function expression is formed when an anonymous Function is assigned to a variable or constant.
  349. */
  350. const sum = add(1, 1); // Throws an Error: TypeError: add is not a function
  351. const add = function(numOne, numTwo) {
  352. return numOne + numTwo;
  353. //};
  354. /*
  355. Above, trying to call add() before it’s assigned will throw an error. The reason for this should be clear - the constant add is yet to be assigned!
  356.  
  357. When using the pattern of Function expressions, you can only call the Function after it’s been assigned to a variable or constant:
  358. */
  359. //const add = function(numOne, numTwo) {
  360. return numOne + numTwo;
  361. //};
  362. const sum = add(1, 1);
  363. console.log(sum); // prints 2, no error...
  364. /*The fact that we can assign Function definitions to a variable or constant is another exmaple of Functions in JavaScript being first class Objects.
  365.  
  366. Calling a Function
  367. To use a Function, we have to call it. Calling a Function will run the code within the body or code block of the Function. Executing, invoking, applying, running are all synonymous with calling a Function.
  368.  
  369. Arguments
  370. Arguments (inputs) are what we call the values passed to a Function when we execute the Function. You can think of arguments like passengers, and paramters like car seats.
  371.  
  372. If we defined a Function with two parameters, thats two car-seats. When we call that Function, we’ll pass in two values, that’s two passengers, one for each car-seat.
  373.  
  374. To call a Function, you must reference its name or the variable name to which its assigned, then pass any values expected.
  375. */
  376. const add = function(numOne, numTwo) {
  377. return numOne + numTwo;
  378. };
  379. const sum = add(1, 1);
  380. console.log(sum); // prints 2
  381. /*We can assign the result of a Function to a variable or constant, like we did in the above example. The result of add(1, 1) was assigned to the constant, sum.
  382.  
  383. Or, we can pass the invocation as a value to another Function as input:
  384. */
  385. const add = function(numOne, numTwo) {
  386. return numOne + numTwo;
  387. };
  388. console.log(add(1, 1)); // prints 2
  389. //In this regard, all Functions are expressions, because they produce a value!
  390.  
  391.  
  392. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  393.  
  394. //Constructor function
  395. //A Constructor Function is a Function invoked to CREATE an INSTANCE of a particular type of value.
  396.  
  397. var car1={
  398. color:'blue',
  399. transmission:'auto',
  400. make:'honda',
  401. horsepower:'90'
  402. }
  403.  
  404. var car2={
  405. color:'red',
  406. transmission:'auto',
  407. make:'yoda',
  408. horsepower:'120'
  409. }
  410.  
  411. //...et. or use the constructor function
  412.  
  413. var Car=function(color,transmission,make,horsepower){
  414. this.color=color;
  415. this.transmission=transmission;
  416. this.make=make;
  417. this.horsepower=horsepower;
  418. }
  419.  
  420. var myCar=new Car('red','manual','yoda',280);
  421. console.log(myCar);
  422. var yourCar=new Car('red', 'auto','ooda',220);
  423. console.log(yourCar);
  424. var ourCar=new Car('blue','auto','yoda',160);
  425. console.log(ourCar);
  426.  
  427.  
  428. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  429.  
  430.  
  431. //scope
  432. Scope
  433. Scope refers to what variables or constants are accessible, where.
  434.  
  435. There are basically two types of scope: Global scope and local.
  436. Global scope is anything outside of Function, and local scopes are local to a Function body.
  437.  
  438. Generally, Functions enclose a scope and protect their variables from parent scopes, including the global scope.
  439.  
  440. Functions can access the variables in their parent scopes! But parent scope cannot access variables in child scopes.
  441.  
  442. //Global Scope
  443. // Here, a is in the global scope, and is visible within the scope of doSomething() //
  444. let a = 1;
  445. function doSomething() {
  446. a = 2;
  447. }
  448. console.log(a); // prints 1
  449. doSomething();
  450. console.log(a); // prints 2
  451.  
  452. In the above example, a is accessible within the body or scope of doSomething(), and can therefore alter the value a contains.
  453.  
  454. In the example below, the variable person is created within the scope of the Function doSomething(), so it is not accessible in the parent scope.
  455.  
  456.  
  457. Function Scope or Local Scope
  458. Local scope refers to declarations that happen within the body of a Function. These declarations are only available within the Function itself and any Functions declared within it.
  459.  
  460. function doSomething() {
  461. var a = 1;
  462. console.log(a);
  463. }
  464. console.log(a); // => throws ReferenceError: a is not defined
  465.  
  466. //Nested Scope
  467. Function can be defined within other Functions, forming nested scopes. In the following example, a is decalred within doSomething(), but is accessible within the child scope of doSomethingElse()!
  468.  
  469. function doSomething() {
  470. let a = 1;
  471. function doSomethingAgain() {
  472. a = 2;
  473. }
  474. doSomethingAgain();
  475. console.log(a); // prints 2
  476. }
  477. doSomething();
  478. But parent scopes do not have access to declarations within children scopes:
  479.  
  480. function doSomething() {
  481. function doSomethingAgain() {
  482. var a = 1;
  483. }
  484. doSomethingAgain();
  485. console.log(a); // => throws ReferenceError: a is not defined
  486. }
  487. doSomething();
  488.  
  489. Function scopes allow us to create privacy - declarations that are not accessible in to other parts of our applcation.
  490.  
  491. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~```
  492.  
  493. Closure
  494. Maintaining access to values by enclosing them in Function bodies
  495.  
  496. Closure
  497. Simply put, a Function definition can carry within its body references to variables in its parent scope. This term is called closure. The Function definition forms a closure around the environment in which it was defined. This means the invocation of the Function has access to variables of its parent scope.
  498.  
  499. function makePerson(nameFirst, nameLast) {
  500. var friends = [];
  501.  
  502. return {
  503. nameFirst: nameFirst,
  504. nameLast: nameLast,
  505. addFriends: function() {
  506. Array.prototype.push.apply(friends, Array.prototype.slice.call(arguments));
  507. },
  508. getNumFriends: function() {
  509. return friends.length;
  510. },
  511. getFriendNames: function() {
  512. return friends.map(function(friend){
  513. return friend.nameFirst + ' ' + friend.nameLast;
  514. })
  515. .join(", ");
  516. }
  517. };
  518. }
  519. Above, when invoking makePerson(), the inner Function definitions of addFriends(), getNumFriends(), getFriendNames() form closures that carry with them a reference to the Array stored in the friends variable.
  520.  
  521. Below, because we keep the person-Object returned from the call to makePerson() in a variable, for example, john, we’ve created a private member. The friends Array is available only through the API of the person-Object. Client code does not have direct access to the friends Array, but as you can see below, it is ALIVE!
  522.  
  523. var john = makePerson('John', 'Fraboni');
  524. var alice = makePerson('Alice', 'Green');
  525. var greg = makePerson('Greg', 'Bara');
  526. john.addFriends(greg, alice);
  527. console.log(john.getFriendNames());</script></body>
  528. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement