Javascript Prototype
Javascript prototype is very useful thing. Say, we want to perform some sort of transformation or something else on string like we want to find some pattern matching for validation. Example below is based on this.
Requires: Javascript
Using:
<script type="text/javascript"> String.prototype.found = null; var str = new String('my string'); function findpat(str) { var gotcha = str.search(/str/i); if(gotcha > 0 ) { return true; } else { return false; } } var ret = findpat(str); str.found = ret; alert(str.found);
- Line 3 is important here as prototype for String is given, so str = ‘my string’ will not work. We have to declare it as String type. Same is to be done if it is being used with other type or custom types.
JSON – Javascript Object Notation
There were days when we used to create and use XML for transporting and store data and it was good at it. But I consider there was a problem with it getting data from it, I feel nausea. I used ‘was’ here because I also consider it as the way our daddies used to transfer data. Now is the day of JSON.
JSON is cool, easy, requires less memory(though we are not bothered). You can use it with any language and I love it. Frankly, I gave up XML before learning it because of JSON.
JSON looks like array we make in C\C++ or any other language. As we are familiar with the array, it makes understanding of JSON easy. It looks like :
{'data' : ['J','S','O','N'], 'this' : { 'is' : 'json' } };
Let’s use it with PHP and Javascript.
PHP:
$array = new array('data'=>array('J','S','O','N'), 'this'=>'json'); $json = json_encode($array); $json = json_decode($json); echo $json->data[0]; //output: J echo $json->this; //output: json
Javascript:
var json = {'data' : ['J','S','O','N'], 'this' : { 'is' : 'json' } }; alert(json['data'][0]); //output: J alert(json->data[0]) //output: J alert(json->this); //output: json alert(json['this']) //output: json
We have studying here for PHP and Javscript as it is used mostly for web development. Go to json.org for better understanding and using with other languages.