Javascript

ECMAScript 5.1 http://www.ecma-international.org/ecma-262/5.1/ECMA-262.pdf (ECMA-262 5.1 Edition / June 2011)

ECMAScript 6.0 (2015) http://www.ecma-international.org/ecma-262/6.0/ECMA-262.pdf

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects

Create an regular expression object

Replace string 'aaa' by 'xyz'.

   1 var stringx = 'aaa bbb ccc';
   2 var regexx = new RegExp('aaa','g');
   3 stringx = stringx.replace( regexx , 'xyz' );

Extract date without certain characters

   1 var currDate = new Date().toISOString();
   2 currDate = currDate.replace( new RegExp('-','g') , '' ).replace( new RegExp(':','g') , '' );
   3 currDate = currDate.substring(0,15);

Delete property from object

   1 delete obj['propertyName'];

Number of milliseconds since epoch

   1 var nrmillis = Date.now();

Foreach in array

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

   1 function logArrayElements(element, index, array) {
   2     console.log("a[" + index + "] = " + element);
   3 }
   4 [2, 5, 9].forEach(logArrayElements);
   5 // logs:
   6 // a[0] = 2
   7 // a[1] = 5
   8 // a[2] = 9
   9 

Context with this and bind

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

   1 /*Constructor function*/
   2 function Counter(){     
   3   this.counter=0;
   4 }
   5 
   6 Counter.prototype.run=function(){
   7   console.log('counter:',this.counter);
   8   this.counter++;
   9   //recall run
  10   setTimeout(this.run.bind(this),1000);
  11 };
  12 
  13 var c = new Counter();
  14 setTimeout( c.run.bind(c) ,1000); // apply context of c to this
  15 

   1 function Counter(name,timeout){     
   2     this.counter=0;
   3     this.name=name;
   4     this.timeout=timeout;
   5 }
   6 
   7 Counter.prototype.run=function(){
   8     console.log('counter:',this.counter,' name:',this.name,' timeout:',this.timeout);
   9     this.counter++;
  10     //recall run
  11     setTimeout(this.run.bind(this),this.timeout);
  12 };
  13 
  14 var c = new Counter('c1',1000);
  15 setTimeout( c.run.bind(c) ,1000);
  16 var d = new Counter('c2',1500);
  17 setTimeout( d.run.bind(d) ,1500);

Two functions manipulate 2 JSON objects passed by this context.

   1 function jsonFactory(c1,c2){
   2   return {'counter1':c1,'counter2':c2};
   3 }
   4 
   5 var data=jsonFactory(0,0);
   6 var data2=jsonFactory(100,100);
   7 
   8 function incCounter1(){
   9   this.counter1++;
  10 }
  11 
  12 function incCounter2(){
  13   this.counter2++;
  14 }
  15 
  16 setInterval(incCounter1.bind(data),1000);
  17 setInterval(incCounter2.bind(data),1000);
  18 setInterval(incCounter1.bind(data2),1000);
  19 setInterval(incCounter2.bind(data2),1000);

arguments

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/arguments

An Array-like object corresponding to the arguments passed to a function.

You can refer to a function's arguments within the function by using the arguments object. This object contains an entry for each argument passed to the function, the first entry's index starting at 0.

bind, JSON and arguments sample

   1 #!/usr/bin/js
   2 // SpiderMonkey JavaScript example code
   3 // simulate console.log in SpiderMonkey
   4 var console={
   5   log: function(msg) {
   6          //putstr( msg + "\n");
   7          print( msg );
   8   }
   9 };
  10 
  11 function add(){
  12   if(this.hasOwnProperty("op1") ) {
  13     console.log("op1 ..." + (this.op1 + this.op2) );
  14   }
  15 
  16   if(this.hasOwnProperty("op3") ) {
  17     console.log("op3 ..." + (this['op3'] + this['op4']) );
  18   }
  19 
  20   if(arguments.length>0) {
  21     console.log( arguments[0]  );
  22   }
  23 }
  24 
  25 //---------------------------------------
  26 console.log("JSON sample ....");
  27 var strx='{"ds":1122 , "hg":"ccvbn" }';
  28 var objx = JSON.parse( strx );
  29 console.log( objx.ds );
  30 console.log( objx.hg );
  31 objx.ds = objx.ds*2;
  32 console.log( objx.ds );
  33 console.log( JSON.stringify( objx )  );
  34 
  35 //---------------------------------------
  36 console.log("bind sample");
  37 var x={"op1":10, "op2":2};
  38 var y={"op3":20, "op4":30};
  39 var z={"op1":10,"op2":13};
  40 var xxx = add.bind(x); // sets the this context with x object
  41 xxx("Arg test") // calls add with an argument
  42 var zzz = add.bind(y); // sets this context with y object
  43 zzz(); // calls add
  44 add.call(z); // sets this context and calls the function add
  45 

Iterate keys in JSON object

   1 for (var key in response.result) {
   2     if (response.result.hasOwnProperty(key)) { 
   3     }
   4 }

Static properties and methods

http://elegantcode.com/2011/01/19/basic-javascript-part-7-static-properties-and-methods/

   1 function Podcast() {};
   2 
   3 Podcast.FILE_EXTENSION = 'mp3'; // static const
   4 
   5 // static method
   6 Podcast.download = function(podcast) {
   7     console.log('Downloading ' + podcast + ' ...');
   8 };
   9 
  10 // instance method
  11 Podcast.prototype.play = function() {
  12     console.log('Playing this podcast ...');
  13 };

ES6 ECMAScript 6 class example

   1 class P{
   2 
   3   // syntax sugar for a constructor function for ES5
   4   // in ES5 would be something like function P(a,b){}
   5   constructor(a,b){
   6     this.a=a;
   7     this.b=b;
   8     // this continues to be context for a function 
   9   }
  10 
  11   // in ES5 would be something like P.prototype.mul = function(){};
  12   mul(){
  13     return this.a*this.b;
  14   }
  15 
  16   // in ES5 would be something like P.sum=function(c,d){};
  17   static sum(c,d){
  18     return c+d;
  19   }
  20 
  21   // in ES5 would be something like p.mulres
  22   get mulres(){
  23     return this.mul();
  24   }
  25 }

JSON pretty print

   1 var str = JSON.stringify(obj, null, 2);

Function based OOP

   1 // Constructor function
   2 function init(value) {
   3   // instance variable
   4   var value = value;
   5 
   6   function dec() {
   7     value--;
   8   }
   9 
  10   function inc() {
  11     value++;
  12   }
  13 
  14   function get() {
  15     return value;
  16   }
  17 
  18   // instance methods
  19   return { 'inc': inc, 'dec': dec, 'get': get };
  20 }
  21 
  22 x = init(10);
  23 y = init(9);
  24 
  25 function other(x1, y1) {
  26   x1['inc']();
  27   x1['inc']();
  28   console.log(x1['get']());
  29   console.log(x1['get']());
  30   y1['dec']();
  31   y1.dec();
  32   console.log(y1['get']());
  33   other2(x1, y1);
  34 }
  35 other(x,y);
  36 function other2(x2, y2) {
  37   x2['inc']();
  38   x2['inc']();
  39   console.log(x2['get']());
  40   console.log(x2['get']());
  41   y2['dec']();
  42   y2.dec();
  43   console.log(y2['get']());
  44 }

Javascript (last edited 2022-02-18 11:53:22 by localhost)