JSFiddle - React, Tailwind, and code Playground
by Ishank Dubey
JavaScript
/*********** The PROTOTYPE example ************/
/*
1.
Prototype Way of adding a method to the Array object itself.
Begin
*/
Array.prototype.myUcase = function(property) {
this.sort(function(a,b){
return a[property] > b[property] ? 1 : a[property] == b[property] ? 0 : -1;
});
};
/*
End
*/
/*
2.
Function to sort array based on the given property.
Begin
*/
function sortArrayByProperty(array, property, ascending){
array.sort(function (a,b){
if(property)
return a[property] > b[property] ? 1 : a[property] == b[property] ? 0 : -1;
else
return a-b;
});
if(!(ascending == undefined || ascending)){
array.reverse();
}
return array;
}
/*
End
*/
/*
Test for 1 and 2
*/
var fruits = [{
name:"20ghi"
},{
name:"20ghi"
},{
name:"11abc"
},{
name:"33"
}];
fruits.myUcase("name");
var i =0, str='' ;
for(i in fruits){
//alert(fruits[i].name + " k");
}
/*
End test for 1 and 2.
*/
/**********The Scope Problem **********/
var anArray = [{index:10, access:function(){return this.index;}},
{index:10, access:function(){return this.index;}},
{index:10, access:function(){return this.index;}}];
/*
3.
Function describing the scope problem
*/
for(var i=0;i<anArray.length;i++){
anArray[i].scopeFuncBad = function(){
alert(i);
}
}
//anArray[0].scopeFuncBad();
//anArray[1].scopeFuncBad();
/*
4.
The Immediately Invoking function can solve the scope problem
*/
for(var i=0;i<anArray.length;i++){
anArray[i].scopeFuncGood = (function(i){
return function(){
alert(i);
};
})(i);
}
//anArray[0].scopeFuncGood();
//anArray[1].scopeFuncGood();