项目作者: mhsunny

项目描述 :
Modern JavaScript ECMAScript 6 and 7, Creating Objects and class, Promises and Callbacks, etc
高级语言: HTML
项目地址: git://github.com/mhsunny/ECMAScript6.git
创建时间: 2019-11-16T02:02:30Z
项目社区:https://github.com/mhsunny/ECMAScript6

开源协议:

下载


“# ECMAScript6 - The Basic of ES6”

Creating Objects and class

  1. <pre>
  2. <code> 'use strict'
  3. class Polygon {
  4. constructor(height, width) {
  5. this.h = height;
  6. this.w = width;
  7. }
  8. test() {
  9. console.log("The height of the polygon: ", this.h)
  10. console.log("The width of the polygon: ", this.w)
  11. }
  12. }
  13. //creating an instance
  14. var polyObj = new Polygon(10, 20);
  15. polyObj.test();
  16. class Recrengel {
  17. constructor(rwidth, rheight) {
  18. this.rw = rwidth;
  19. this, rh = rheight;
  20. }
  21. createRec() {
  22. console.log("The height of the polygon: ", this.rh)
  23. console.log("The width of the polygon: ", this.rw)
  24. }
  25. }
  26. //creating an instance
  27. var recObj = new Recrengel(100, 80);
  28. myrec = recObj.createRec();
  29. console.log("rectangle: " + myrec);
  30. </code>
  31. </pre>
  32. <script>
  33. 'use strict'
  34. class Polygon {
  35. constructor(height, width) {
  36. this.h = height;
  37. this.w = width;
  38. }
  39. test() {
  40. console.log("The height of the polygon: ", this.h)
  41. console.log("The width of the polygon: ", this.w)
  42. }
  43. }
  44. //creating an instance
  45. var polyObj = new Polygon(10, 20);
  46. polyObj.test();
  47. console.log("rectangle: " + myrec);
  48. class Recrengel {
  49. constructor(rwidth, rheight) {
  50. this.rw = rwidth;
  51. this.rh = rheight;
  52. }
  53. createRec() {
  54. // console.log("The height of the polygon: ", this.rh)
  55. // console.log("The width of the polygon: ", this.rw)
  56. return this.rh * this.rw;
  57. }
  58. }
  59. //creating an instance
  60. var recObj = new Recrengel(100, 80);
  61. var myrec = recObj.createRec();
  62. console.log("rectangle: " + myrec);
  63. </script>
  64. <script>
  65. 'use strict'
  66. class PrinterClass {
  67. doPrint() {
  68. console.log("doPrint() from Parent called…")
  69. }
  70. }
  71. class StringPrinter extends PrinterClass {
  72. doPrint() {
  73. super.doPrint()
  74. console.log("doPrint() is printing a string…")
  75. }
  76. }
  77. var obj = new StringPrinter()
  78. obj.doPrint()
  79. </script>

Promises and Callbacks.

  1. <pre>
  2. function notifyAll(fnSms, fnEmail) {
  3. setTimeout(function() {
  4. console.log('starting notification process');
  5. fnSms();
  6. fnEmail();
  7. }, 2000);
  8. }
  9. notifyAll(
  10. function() {
  11. console.log("Sms send ..");
  12. },
  13. function() {
  14. console.log("email send ..");
  15. }
  16. );
  17. console.log("End of script"); //executes first or not blocked by others
  18. <script>
  19. function notifyAll(fnSms, fnEmail) {
  20. setTimeout(function() {
  21. console.log('starting notification process');
  22. fnSms();
  23. fnEmail();
  24. }, 2000);
  25. }
  26. notifyAll(
  27. function() {
  28. console.log("Sms send ..");
  29. },
  30. function() {
  31. console.log("email send ..");
  32. }
  33. );
  34. console.log("End of script"); //executes first or not blocked by others
  35. </script>

  1. #Understanding Callback
  2. <pre>
  3. <code>
  4. function getSum(n1, n2) {
  5. var isAnyNegative = function() {
  6. return n1 < 0 || n2 < 0;
  7. }
  8. var promise = new Promise(function(resolve, reject) {
  9. if (isAnyNegative()) {
  10. reject(Error("Negatives not supported"));
  11. }
  12. resolve(n1 + n2);
  13. });
  14. return promise;
  15. }
  16. getSum(5, 6)
  17. .then(function(result) {
  18. console.log(result);
  19. return getSum(10, 20);
  20. //this returns another Promise
  21. },
  22. function(error) {
  23. console.log(error);
  24. })
  25. .then(function(result) {
  26. console.log(result);
  27. return getSum(30, 40);
  28. //this returns another Promise
  29. },
  30. function(error) {
  31. console.log(error);
  32. })
  33. .then(function(result) {
  34. console.log(result);
  35. },
  36. function(error) {
  37. console.log(error);
  38. });
  39. console.log("End of script ");
  40. </code>
  41. </pre>
  42. <script>
  43. function getSum(n1, n2) {
  44. var isAnyNegative = function() {
  45. return n1 < 0 || n2 < 0;
  46. }
  47. var promise = new Promise(function(resolve, reject) {
  48. if (isAnyNegative()) {
  49. reject(Error("Negatives not supported"));
  50. }
  51. resolve(n1 + n2);
  52. });
  53. return promise;
  54. }
  55. getSum(5, 6)
  56. .then(function(result) {
  57. console.log("1st res: " + result);
  58. return getSum(10, 20);
  59. //this returns another Promise
  60. },
  61. function(error) {
  62. console.log("1st error: " + error);
  63. })
  64. .then(function(result) {
  65. console.log("2nd res: " + result);
  66. return getSum(30, -40);
  67. //this returns another Promise
  68. },
  69. function(error) {
  70. console.log("2nd error: " + error);
  71. })
  72. .then(function(result) {
  73. console.log("3rd res: " + result);
  74. },
  75. function(error) {
  76. console.log("3rd error: " + error);
  77. });
  78. console.log("End of script ");
  79. </script>
  80. <script>
  81. import display_message from 'MessageModule.js'
  82. display_message()
  83. </script>
  84. #JavaScript Module
  85. <pre>
  86. <p>math.js</p>
  87. export {
  88. sumAll as
  89. default
  90. };
  91. export {
  92. sumAll,
  93. subtractAll,
  94. divideAll,
  95. multiplyAll
  96. };
  97. let sumAll = (a, b) => {
  98. return a + b;
  99. }
  100. let subtractAll = (a, b) => {
  101. return a - b;
  102. }
  103. let divideAll = (a, b) => {
  104. return a / b;
  105. }
  106. let multiplyAll = (a, b) => {
  107. return a * b;
  108. }
  109. let findModulus = (a, b) => {
  110. return a % b;
  111. <p>app.js</p>
  112. import * as math from './math.js';
  113. console.log(math.multiplyAll(9, 8));
  114. </pre>
  115. #Immediately Invoked Function Expression
  116. <code>
  117. var main = function() {
  118. (function() {
  119. for (var x = 0; x < 5; x++) {
  120. console.log(x);
  121. }
  122. })();
  123. console.log("x can not be accessed outside the block scope x value is :" + x);
  124. }
  125. main();
  126. </code>
  127. <script>
  128. var main = function() {
  129. (function() {
  130. for (var x = 0; x < 5; x++) {
  131. console.log(x);
  132. }
  133. })();
  134. console.log("x can not be accessed outside the block scope x value is :" + x);
  135. }
  136. main();
  137. </script>
  138. <h2>Generator Functions
  139. </h2>
  140. <code>
  141. "use strict"
  142. function* rainbow() {
  143. // the asterisk marks this as a generator
  144. yield 'red';
  145. yield 'orange';
  146. yield 'yellow';
  147. yield 'green';
  148. yield 'blue';
  149. yield 'indigo';
  150. yield 'violet';
  151. }
  152. for (let color of rainbow()) {
  153. console.log(color);
  154. }
  155. </code>
  156. <script>
  157. "use strict"
  158. function* rainbow() {
  159. // the asterisk marks this as a generator
  160. yield 'red';
  161. yield 'orange';
  162. yield 'yellow';
  163. yield 'green';
  164. yield 'blue';
  165. yield 'indigo';
  166. yield 'violet';
  167. }
  168. for (let color of rainbow()) {
  169. console.log(color);
  170. }
  171. </script>
  172. <h2>The Object.assign() Function
  173. </h2>
  174. <script>
  175. "use strict"
  176. var det = {
  177. name: "Tom",
  178. ID: "E1001"
  179. };
  180. var copy = Object.assign({}, det);
  181. // console.log(copy);
  182. for (let val in copy) {
  183. console.log(copy[val])
  184. }
  185. </script>
  186. <h2>Invoked through call or apply</h2>
  187. <script>
  188. var adder = {
  189. base: 1,
  190. add: function(a) {
  191. var f = v => v + this.base;
  192. return f(a);
  193. },
  194. addThruCall: function(a) {
  195. var f = v => v + this.base;
  196. var b = {
  197. base: 2
  198. };
  199. return f.call(b, a);
  200. },
  201. addMore: function(a) {
  202. var f = v => v + this.base;
  203. var b = {
  204. base: 4
  205. };
  206. return f.call(b, a);
  207. }
  208. };
  209. console.log("Invoked through call or apply");
  210. console.log(adder.add(1)); // This would log 2
  211. console.log(adder.addThruCall(1)); // This would log 2 still
  212. console.log(adder.addMore(2));
  213. </script>
  214. #No binding of arguments
  215. <script>
  216. var arguments = [1, 2, 3];
  217. var arr = () => arguments[0];
  218. arr(); // 1
  219. function foo(n) {
  220. var f = () => arguments[0] + n; // foo's implicit arguments binding. arguments[0] is n
  221. return f();
  222. }
  223. function bar(n) {
  224. var b = () => arguments[0] + n;
  225. return b();
  226. }
  227. console.log("No binding of arguments ");
  228. foo(3); // 6
  229. console.log("foo" + foo(3));
  230. console.log("BAR " + bar(2));
  231. </script>
  232. <h2>JavaScript Class</h2>
  233. <p>In this example we demonstrate a simple class definition and how to use it.</p>
  234. <code>
  235. class Car {
  236. constructor(brand) {
  237. this.carname = brand;
  238. }
  239. }
  240. class Motor {
  241. constructor(name) {
  242. this.motorname = name;
  243. }
  244. }
  245. mymotor = new Motor("General Motor");
  246. mycar = new Car("Ford");
  247. document.getElementById("demo").innerHTML = mymotor.motorname;
  248. </code>
  249. <p id="demo"></p>
  250. <script>
  251. class Car {
  252. constructor(brand) {
  253. this.carname = brand;
  254. }
  255. }
  256. class Motor {
  257. constructor(name) {
  258. this.motorname = name;
  259. }
  260. }
  261. mymotor = new Motor("General Motor");
  262. mycar = new Car("Ford");
  263. document.getElementById("demo").innerHTML = mymotor.motorname;
  264. </script>
  265. <h2>Array.find()</h2>
  266. <p id="demo2"></p>
  267. <script>
  268. var numbers = [4, 9, 16, 25, 29];
  269. var first = numbers.find(myFunction);
  270. document.getElementById("demo2").innerHTML = "First number over 18 is " + first;
  271. function myFunction(value, index, array) {
  272. return value > 18;
  273. }
  274. </script>
  275. <h2>Number Object Properties</h2>
  276. <p>MIN_SAFE_INTEGER</p>
  277. <p id="demo3"></p>
  278. <p>MAX_SAFE_INTEGER</p>
  279. <p id="demo4"></p>
  280. <script>
  281. var y = Number.MIN_SAFE_INTEGER;
  282. var x = Number.MAX_SAFE_INTEGER - 1;
  283. document.getElementById("demo4").innerHTML = x;
  284. document.getElementById("demo3").innerHTML = y;
  285. </script>
  286. <h2>JavaScript Number Methods</h2>
  287. <p>The isInteger() method returns true if the argument is an integer.</p>
  288. <p>Otherwise it returns false.</p>
  289. Number.isInteger(10) + "<br>" + Number.isInteger(10.5);
  290. <p id="demo5"></p>
  291. <script>
  292. document.getElementById("demo5").innerHTML =
  293. Number.isInteger(10) + "<br>" + Number.isInteger(10.5);
  294. </script>
  295. <h2>JavaScript Number Methods</h2>
  296. <p>The isSafeInteger() method returns true if the argument is a safe integer.</p>
  297. <p>Otherwise it returns false.</p>
  298. Number.isSafeInteger(10) + "<br>" + Number.isSafeInteger(12345678901234567890);
  299. <p id="demo6"></p>
  300. <script>
  301. document.getElementById("demo6").innerHTML =
  302. Number.isSafeInteger(10) + "<br>" + Number.isSafeInteger(12345678901234567890);
  303. </script>
  304. <h2>JavaScript Number Methods</h2>
  305. <p>The isFinite() method returns false if the argument is Infinity or NaN.</p>
  306. <p>Otherwise it returns true.</p>
  307. isFinite(10 / 0) + "<br>" + isFinite(10 / 1);
  308. <p id="demo7"></p>
  309. <script>
  310. document.getElementById("demo7").innerHTML =
  311. isFinite(10 / 0) + "<br>" + isFinite(10 / 1);
  312. </script>
  313. <h2>The ** Operator</h2>
  314. <p id="demo8"></p>
  315. <script>
  316. var x = 10;
  317. document.getElementById("demo8").innerHTML = x ** 2;
  318. </script>
  319. <h2>JavaScript Array.forEach()</h2>
  320. <p>Calls a function once for each array element.</p>
  321. var txt = "";</br>
  322. var numbers = [45, 4, 9, 16, 25];</br>
  323. numbers.forEach(myFunction);</br>
  324. document.getElementById("demo10").innerHTML = txt;</br>
  325. function myFunction(value) {</br>
  326. txt = txt + value + "<br>"; }
  327. </br>
  328. <p id="demo10"></p>
  329. <script>
  330. var txt = "";
  331. var numbers = [45, 4, 9, 16, 25];
  332. numbers.forEach(myFunction);
  333. document.getElementById("demo10").innerHTML = txt;
  334. function myFunction(value) {
  335. txt = txt + value + "<br>";
  336. }
  337. </script>
  338. <h2>JavaScript Array.filter()</h2>
  339. <p>Creates a new array with all array elements that passes a test.</p>
  340. <p id="demo12"></p>
  341. <script>
  342. var numbers = [45, 4, 9, 16, 25];
  343. var over18 = numbers.filter(myFunction);
  344. document.getElementById("demo12").innerHTML = over18;
  345. function myFunction(value, index, array) {
  346. return array;
  347. }
  348. </script>
  349. <h2>JavaScript Array.reduce()</h2>
  350. <p>This example finds the sum of all numbers in an array:</p>
  351. var sum = numbers.reduce(myFunction)<br> document.getElementById("demo").innerHTML = "The sum is " + sum
  352. <br> function myFunction(total, value, index, array) {<br> return total + value<br> }
  353. <br>
  354. <p id="demo13"></p>
  355. <script>
  356. var numbers = [45, 4, 9, 16, 25];
  357. var sum = numbers.reduce(myFunction);
  358. document.getElementById("demo13").innerHTML = "The sum is " + sum;
  359. function myFunction(total, value, index, array) {
  360. return total + value;
  361. }
  362. </script>
  363. <h2>JavaScript Array.every()</h2>
  364. <p>The every() method checks if all array values pass a test.</p>
  365. <code>
  366. var numbers = [45, 4, 9, 16, 25];
  367. var allOver18 = numbers.every(myFunction);
  368. document.getElementById("demo14").innerHTML = "All over 18 is " + allOver18;
  369. function myFunction(value, index, array) {
  370. return value > 18;
  371. }
  372. </code>
  373. <p id="demo14"></p>
  374. <script>
  375. var numbers = [45, 4, 9, 16, 25];
  376. var allOver18 = numbers.every(myFunction);
  377. document.getElementById("demo14").innerHTML = "All over 18 is " + allOver18;
  378. function myFunction(value, index, array) {
  379. return value > 18;
  380. }
  381. </script>
  382. <h2>JavaScript Array.indexOf()</h2>
  383. <p id="demo15">/p>
  384. <script>
  385. var fruits = ["Apple", "Orange", "Apple", "Mango"];
  386. var a = fruits.indexOf("Orange");
  387. document.getElementById("demo15").innerHTML = "Orange is found in position " + a;
  388. </script>
  389. <h2>Create Object from JSON String</h2>
  390. <code>
  391. var txt = '{"name":"John", "age":30, "city":"New York"}'
  392. var obj = JSON.parse(txt);
  393. document.getElementById("demo16").innerHTML = obj.name + ", " + obj.age;
  394. </code>
  395. <p id="demo16"></p>
  396. <script>
  397. var txt = '{"name":"John", "age":30, "city":"New York"}'
  398. var obj = JSON.parse(txt);
  399. document.getElementById("demo16").innerHTML = obj.name + ", " + obj.age;
  400. </script>
  401. <h2>Create JSON string from a JavaScript object.</h2>
  402. <code>
  403. var obj = {
  404. name: "John",
  405. age: 30,
  406. city: "New York"
  407. };
  408. var obj2 = {
  409. name: "sunny",
  410. age: 30,
  411. city: "NY"
  412. };
  413. var myJSON = JSON.stringify(obj2);
  414. document.getElementById("demo17").innerHTML = myJSON;
  415. </code>
  416. <p id="demo17"></p>
  417. <script>
  418. var obj = {
  419. name: "John",
  420. age: 30,
  421. city: "New York"
  422. };
  423. var obj2 = {
  424. name: "sunny",
  425. age: 30,
  426. city: "NY"
  427. };
  428. var myJSON = JSON.stringify(obj2);
  429. document.getElementById("demo17").innerHTML = myJSON;
  430. </script>
  431. <h2>ES6 and Variable Hoisting</h2>
  432. <code>
  433. var main = function() {
  434. for (var x = 0; x < 5; x++) {
  435. console.log(x);
  436. }
  437. console.log("x can be accessed outside the block scope x value is :" + x);
  438. console.log('x is hoisted to the function scope');
  439. document.getElementById("demo18").innerHTML = x;
  440. }
  441. main();
  442. </code>
  443. <p id="demo18"></p>
  444. <script>
  445. var main = function() {
  446. for (var x = 0; x < 5; x++) {
  447. console.log(x);
  448. }
  449. console.log("x can be accessed outside the block scope x value is :" + x);
  450. console.log('x is hoisted to the function scope');
  451. document.getElementById("demo18").innerHTML = x;
  452. }
  453. main();
  454. </script>
  455. <h2>No binding of arguments
  456. </h2>
  457. <p id="demo19"></p>
  458. <script>
  459. function foo(n) {
  460. var f = (...args) => args[0] + n;
  461. return f(10);
  462. }
  463. num = foo(1); // 11
  464. document.getElementById("demo19").innerHTML = num;
  465. console.log(num);
  466. </script>
  467. <h2>Arrow functions used as methods</h2>
  468. <p>As stated previously, arrow function expressions are best suited for non-method functions. Let's see what
  469. </p>
  470. 'use strict';<br> var obj = { // does not create a new scope<br> i: 10,<br> b: () => console.log(this.i, this),<br> c: function() {<br> console.log(this.i, this);<br> }
  471. <br> }
  472. <br>
  473. <br> obj.b(); // prints undefined, Window {...} (or the global object)<br> obj.c(); // prints 10, Object {...}<br>
  474. <script>
  475. 'use strict';
  476. var obj = { // does not create a new scope
  477. i: 10,
  478. b: () => console.log(this.i, this),
  479. c: function() {
  480. console.log(this.i, this);
  481. }
  482. }
  483. obj.b(); // prints undefined, Window {...} (or the global object)
  484. obj.c(); // prints 10, Object {...}
  485. </script>
  486. <h2>The Function Constructor
  487. </h2>
  488. var func = new Function("x", "y", "return x*y;"); <br> function product() { <br> var result; <br> result = func(10,20); <br> console.log("The product : "+result)<br> } product()
  489. <script>
  490. var func = new Function("x", "y", "return x*y;");
  491. function product() {
  492. var result;
  493. result = func(10, 20);
  494. console.log("The product : " + result)
  495. }
  496. product();
  497. </script>