Jump to content

prototype in javascript


ashri

Recommended Posts

Here is an example of extending a JavaScript prototype:

String.prototype.explode = function() {  var exploded = new Array();  for(i=0;i<this.length;i++) {	exploded[i] = this.substr(i, 1);  }  return exploded;}

This function splits a string into single characters, each one occupying the next space in an array. For example:if the variable testString = 'hi there', then testString.explode() would return:

array { [0] => h [1] => i [2] =>  [3] => t [4] => h [5] => e [6] => r [7] => e}

The syntax is very straightforward: ObjectName.prototype.methodName = function() { }So, if you want to extend the string object, then replace ObjectName with String, and replace methodName with whatever you want your new method to be called, and then define the function within the braces. I believe you always need to return from the function.

Link to comment
Share on other sites

Some advice. If this goes over your head, just ignore it. I am writing for anyone who cares.The use of the for-in structure on a normal array behaves as you would expect. The loop iterates through elements that your code has added to the array, and only those elements. Because of the way that JavaScript is structured internally, properties and methods that belong to the Array prototype are ignored.However, when your script adds properties or methods to the Array prototype, JavaScript cannot (at this time) distinguish between them and elements that are added to the array using traditional array techniques. This means that a for-in structure will iterate through your array elements AND any properties and methods you have added to the Array prototype. For this reason, it is generally best not to use a for-in structure when you have re-prototyped the Array object.Many libraries and frameworks re-prototype the array object, and they recommend the same thing.An illustration of the problem:

var i;var s="";var a = ["Hello", "Nice Day", "Bye"]for (i in a) {   s += a[i] +" ";}alert(s); // "Hello Nice Day Bye"// now we change the prototypeArray.prototype.myName = "DD";for (i in a) {   s += a[i] +" ";}alert(s); // "DD Hello Nice Day Bye"

This may not be what you expected, but it is what you will get. It's even uglier if you add a method to the prototype.One solution is to use an Array object only for numerically indexed arrays, and then always iterate through the array using a numerical technique. If you need an associative array, use an Object constructor instead. Now you can safely iterate through your associative "array" using the for-in structure. Just don't re-prototype the Object object.Future versions of JavaScript will allow you to toggle a switch on re-prototyped elements that will hide them from the for-in structure.

Link to comment
Share on other sites

  • 9 months later...
Here is an example of extending a JavaScript prototype:
String.prototype.explode = function() {  var exploded = new Array();  for(i=0;i<this.length;i++) {	exploded[i] = this.substr(i, 1);  }  return exploded;}

This function splits a string into single characters, each one occupying the next space in an array. For example:if the variable testString = 'hi there', then testString.explode() would return:

array { [0] => h [1] => i [2] =>  [3] => t [4] => h [5] => e [6] => r [7] => e}

The syntax is very straightforward: ObjectName.prototype.methodName = function() { }So, if you want to extend the string object, then replace ObjectName with String, and replace methodName with whatever you want your new method to be called, and then define the function within the braces. I believe you always need to return from the function.

Your code is interesting to me, yet not comprehensible. Could you write a couple of scripts that we can really put in practice?And I wrote a similar script with reference to you guys' demonstration to achieve the split-words effect:
<script>var txt = 'hello world';document.write('JS: substring(start,end):' + '<br />');for (i=0; i<=txt.length-1; i++){	document.write(txt.substring(i,i+1) + '<br />');	}document.write('<hr />')	document.write('JS: substr(start,length):' + '<br />');for (n=0; n<=txt.length-1; n++){	document.write(txt.substr(n,1) + '<br />');	}document.write('<hr />');</script>

That's why I am still confused with the use of prototype in your script. I know prototype is to add more to an object. But just cannot figure out how prototype works in your example.

Link to comment
Share on other sites

old thread, but here goes

String.prototype.explode = function() {  var exploded = new Array();  for(i=0;i<this.length;i++) {	exploded[i] = this.substr(i, 1);  }  return exploded;}

well, the whole point of prototyping is so that from then on all future objects of that name will have access to that custom method added by prototyping. Here's an example implementation, just like he said.

var myString = "This is a string";var explodedMyString = myString.explode();

It's just a very basic example. Strings are array's anyway, so returning an array isn't entirely the most enlightening example, but it was only meant for illustrative purposes, I believe.

Link to comment
Share on other sites

The advantage to reprototyping a built-in object, like a string or an array, is that every time you need to perform the new method, it is available in a form that requires the least amount of code.The code Tin provides can only be executed once, as the document downloads. After the document has downloaded, calls to document.write obliterate the existing page and create a new document. This is not very useful.What else are you confused about? Be very specific.

Link to comment
Share on other sites

The advantage to reprototyping a built-in object, like a string or an array, is that every time you need to perform the new method, it is available in a form that requires the least amount of code.The code Tin provides can only be executed once, as the document downloads. After the document has downloaded, calls to document.write obliterate the existing page and create a new document. This is not very useful.What else are you confused about? Be very specific.
So how can this be executed more than once, without any obliteration?I'm still confused with thescientist's script:
String.prototype.explode = function() { var exploded = new Array(); for(i=0;i<this.length;i++) { exploded = this.substr(i, 1); } return exploded;}var myString = "This is a string";var explodedMyString = myString.explode();
var exploded = new Array();But I cannot see where the arrary is and is referred to.Is var myString the array? As I can seeexploded = this.substr(i,1);Is that because var explodedMyString = myString.explode() links myString to the function explode()? And,Why is there in the very beginning String?I'm sorry if I cannot make my questions understandable. But I can hardly process how prototype operates (has been the most difficult JS part to me~).
Link to comment
Share on other sites

var myString = "This is a string";var explodedMyString = myString.explode();

These two lines show you how to use the new method. They demonstrate that after the prototype has been changed, ANY string can be exploded into an array using the explode method. myString is not an array. It is a normal string. explodedMyString is the return value of myString.explode(), so it is the array. The value of explodedMyString[0] is the first character of myString, which is "T".Often, a developer will begin the process of re-prototyping by writing a stand-alone function. The explode method we're looking at could also have been written that way. It might look like this:

function explode(str) {  var exploded = new Array();  for (var i = 0; i < str.length; i++) {	exploded[i] = str.substr(i, 1);  }  return exploded;}

You would use it like this:

var myString = "This is a string";var explodedMyString = explode(myString);// some stupid examplesalert(explodedMyString[0]); // "T"alert(explodedMyString[1]); // "h"alert(explodedMyString[2]); // "i"alert(explodedMyString[3]); // "s"

See how they are very similar? The re-prototyping process can be thought of as a way of turning a standalone function into a method of the String object.If you have questions about the new method, try first to understand the explode function I just showed you. If you have questions about that, please ask. When you understand it completely, compare it with the String.explode method. There are some differences. If they confuse you, please ask.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...