You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
vararray=[];varobject={};varmethod=function(){};varinstance=newfunction(privateField,a,b){// allows all instance methods and fields to have access to the current instance.varme=this;// creates a private method, only accesible to methods inside instancefunctionprivateMethod(){}// creates a private method, accessible to only methods inside instancefunctionprivateMethod(){// callbacks and private methods dont have access to `this`, so we use `me`this.publicMethod();// badme.publicMethod();// good}// creates a public method, accessible to methods inside and outside the instancethis.publicMethod=function(){// public methods can call private methodsprivateMethod();};// creates a public field.this.publicField=privateField;// creates public fields referring to private fields.this.b=a;this.a=b;};// can not call private instance methodsinstance.privateMethod();// bad// can call public instance methods.instance.publicMethod();// good
Map and Reduce Example
// create a map functionvarmap=function(array,callback){// initialize an empty results arrayvarresults=[];// loop through each element in the passed array, run it through the callback method, add it to the results arrayfor(variinarray){results[i]=callback(array[i],i);}returnresults;};// create a reduce function with the starting value, array of things to callback through, // and the function to mess with the arrayvarreduce=function(initial,array,callback){// set the starting valuevarresult=initial;// loop through the passed array, modify the current result value with the callbackfor(variinarray){result=callback(result,array[i],i);}returnresult;};// create an example function which applies map and reducevarsum=function(values,callback){returnreduce(// set the starting value0,// let the map function pass through the value and callbackmap(values,callback),// this is the callback for reduce. It just adds the current value of the mapped array to the // current total, which is why this function is called sum.function(result,value){returnresult+value;});};// log to the browser consoleconsole.log(// call our example sum functionsum(// specify an array of starting numbers[5,6,7],// specify a callback to optionally transform each element of this array with map()function(value){// this function doesn't do any transforming before summing upreturnvalue;}// sum will take care of adding each item to the result and returning the result.));