« Previous entry | Next entry » Browse > Snippets

Skip to comments (24) [Javascript] The prototype attribute
Posted by Erik on Jan 19 2006 @ 16:48  :: 5663 unique visits

What is it


Lots of people have heard about or seen the prototype attribute but only a few know how to use it (if you already know about it, skip to Extending the Function class below).
The prototype attribute is a class attribute which can be used to add functionallity to classes.

Some simple code:
CODE: JAVASCRIPT
// a simle class
function MyClass() {
  this.foo = function() {
    return 42;
  }
}

// 2 instances of the class
var a = new MyClass();
var b = new MyClass();

// add a function to a (instance of MyClass)
a.bar = function() {
  return 1337;
}

b.bar(); // will give an error because the function only exists for a
 

This will only add functionallity to the instance of a class. Sometimes you want to add functionallity to the class itself.
This is what the prototype attribute is for:
CODE: JAVASCRIPT
// add the bar function to the class
MyClass.prototype.bar = function() {
  return 1337;
}

var c = new MyClass();

c.bar(); // this will return 1337
 

Where to use it


Adding functionallity to your own classes this way may seem a bit strange because you can just add it to your class definition. But you can't do this for buildin classes such as the Array class:
CODE: JAVASCRIPT
// add a find function to the Array class.
Array.prototype.find = function(item) {
  for (var i = 0; i < this.length; i++) {
    if (this[i] == item) {
      return i; // return the index
    }
  }
  return false;
}

var foo = new Array('hi', 'there', 'this', 'is', 'a', 'test');

foo.find('is'); // will return 3
 


Extending the Function class


Warning: advanced readers only!

Because in javascript functions are also classes the prototype attribute can be used to do some cool stuff with functions. Check these 2 functions:
CODE: JAVASCRIPT
Function.prototype.before = function(b) {
  var a = this;
  return function() {
    a();
    b();
  }
};
Function.prototype.after = function(a) {
  return a.before(this);
};


Example usage:
CODE: JAVASCRIPT
function foo() {
  alert('foo');
}
function bar() {
  alert('bar');
}

foobar = foo.before(bar);

foobar(); // call foo and then bar

foobar.after(bar)(); // call bar then foo and then bar again
 

This can be used to creat a chain of functions which can sometimes be usefull for events:
CODE: JAVASCRIPT
function FunctionChain() {
  this.call = function() { ; } // starting function does nothing

  this.add = function(f) {
    this.call = (this.call).before(f);
  }
}

var c = new FunctionChain();
c.add(foo);
c.add(foo);
c.add(bar);
c.call(); // this will call them in order they are added: foo, foo, bar
 

This will not work for functions which expect arguments. So lets add a function to the Function class which will allows you to make a closure from a function:
CODE: JAVASCRIPT
Function.prototype.toClosure = function() {
  var f = this;
  var a = arguments;
  return function() {
    return f.apply(this, a);
  }
}

Now you can do stuff like this:
CODE: JAVASCRIPT
// use the same foo function as above but defina a new bar function
function bara(a, b) {
  alert('bara: '+(a * b);
}

var foobara = bara.toClosure(42, 1337).after(foo);
foobara();

Isn't that cool?

24 comments posted so far
Add your own »

1. On Jan 20 2006 @ 12:04 Erik wrote:

The toClosure function normally doesn't work on alert because alert isn't a normal Function object and doesn't like apply. You will get a uncaught exception: Illegal operation on WrappedNative prototype object.
Here is a way to fix this:
CODE: JAVASCRIPT
var __alert = alert;    // the old alert
alert = function(str) { // the new alert
  __alert(str);
}

setTimeout(alert.toClosure('foobar'), 1000);

2. On Jan 20 2006 @ 15:18 Erik wrote:

I modiefied the toClosure function to allow the function to return something and to fix the scope the function is executed in.
You can now do this:
CODE: JAVASCRIPT
function foo(bar) {
  alert(bar+' : '+this.href);
  return false;
}

var somelink = document.getElementById('somelink');
somelink.onclick = foo.toClosure(42);


Post about an even more improved toClosure

3. On Feb 14 2006 @ 10:58 Matthijs wrote:

nice :)
CODE: JAVASCRIPT
HTMLElement = document.createElement("bla").constructor;
HTMLElement.prototype.setColor(s) {
   this.style.color = s;
};

4. On Aug 27 2008 @ 04:53 guest wrote:

Top 10 best <a href=http://www.roulettesystemwinner.com>roulette strategy</a> gambling casinos based on micro gaming platform.
Best <a href=http://www.blackjack21onlinestrategy.com>play blackjack online</a> gambling casinos, play to win and enjoy your online
<a href=http://www.blackjack-collection.net>blackjack software</a> experience.
Learn how to play <a href=http://www.win-online-video-poker.com>video poker gambling</a> and experience the thrill of gambling and beating online casinos.
Use a free <a href=http://www.poker-mastery.com>poker guide</a> to calculate your winning poker odds.
Learn the art of <a href=http://www.winninghorseracingbets.com>gambling horse racing</a> and play to win your punts at the races.
Dont buy movies, get <a href=http://www.mymovie-downloads.com>movie downloading</a> movies and watch them for free.
Earn money and work from home, with <a href=http://www.forexmarkettrader.net>learn forex</a>, trade the forex market.
Get all sorts of <a href=http://www.iphone-shaq.com>iphone</a> for your new iphone mobile telephone.

5. On Aug 27 2008 @ 04:53 guest wrote:

Top 10 best online roulette gambling casinos based on micro gaming platform.
Best online blackjack gambling casinos, play to win and enjoy your online
casino blackjack experience.
Learn how to play online video poker and experience the thrill of gambling and beating online casinos.
Use a free poker calculator to calculate your winning poker odds.
Learn the art of horse racing betting and play to win your punts at the races.
Dont buy movies, get bootleg movie download movies and watch them for free.
Earn money and work from home, with forex training, trade the forex market.
Get all sorts of iphone downloads for your new iphone mobile telephone.

6. On Apr 18 2009 @ 08:55 Scott wrote:

I am new to learn web programming in php, java script, css etc. You have written a useful piece of code for ‘The prototype attribute’. It looks handy and error free. At present I am bust in preparation for 640-721 Exam for Implementing Cisco Unified Wireless Networking Essentials (IUWNE) and 70-643 Exam to be held end of this month. That’s why I will test this piece of code after my exams. I am also paying attention to go for 640-816 Exam by Cisco Corporation. All these exams are good enough for the better and bright future. Some other exams like 350-029 can also be considered good. Again thanks for the great piece of code.

7. On May 13 2009 @ 15:47 guest wrote:

Need Furniture? And need to buy furniture from China at competitive price? LongYear Furniture is your source for quality bedroom furniture featuring a huge selection of home furniture a happy home for beautiful life, kids furniture for a good memory of childhood, and to gain an extra good price from wholesale furniture and direct from  furniture manufacturers China, styles of China furniture are available, living room furniture is also nice for your house, find dining room furniture and more!

8. On May 25 2009 @ 08:05 maryzheng wrote:

An embroidery machine manufacturer and supplier of embroidery machine equipment, We are energy saving lamp enterprises,yield energy saving lamp,sales energy saving lamp.
The laminate flooring Guide is the A to Z of laminate flooring and professinal Punch press, our technology of Punch press is very advanced.You can not only order a water pumps, Honda Water Pump, Car jet pump, Auto jet pump OEM Manufacturer of switching power supply,Switching Power Supply Design and power inverter provider, also is a temperature sensor manufacturer, china auto parts.Precision sheet metal fabrication: Click to learn more about custom,precision sheet metal fabrication.The expansion valve manufacturers and expansion valve

10. On Jun 29 2009 @ 11:06 hard13jww wrote:

I have not updated my <a href="http://www.wowgold-de.com" title="wow gold">wow gold</a>blog for the ages. In fact, I was too busy to<a href="http://www.wowgoldlive.de" title="wow gold">wow gold</a> even a visit to. And it was not a lame <a href="http://www.wowtao.de" title="wow gold">wow gold</a>excuse for "lazy". For the <a href="http://www.wowtao.fr" title="wow gold">wow gold</a>last month, the translation orders rushed, like snowflakes from everywhere: the Internet, my friends and <a href="http://www.gogoer.fr" title="wow gold">wow gold</a>my company.

11. On Jun 29 2009 @ 11:08 hard13jww wrote:

I have not updated my blogwow gold for the ages. In fact, I was too busy to even a visit to. And it was not wow golda lame excuse for "lazy". For the last month, the translation orders rushed, like snowflakeswow gold from everywhere: the Internet, my friends and my company. I knew it could bewow gold a unique opportunity, and I did not want to miss one of them. So I am wow goldImmerse yourself in a project I could get, and I was deeply buried in my work. Mounting pressure, the expectations wow goldwere high and the work will be more and more. I was hardly anywow gold time left for anything else. The customers always expect high-performance andwow gold fast-as-possible delivery. Every projectwow gold  that I was obliged likewow gold eur a battlefield, where I was not only in the wow gold eurfight against time, with words, but also with the boundaries of personal knowledge.

12. On Jun 29 2009 @ 11:10 hard13jww wrote:

I was to write a wow poshort speech about the new service wow orto introduce, within an hour. I had until wow geldthe end of 6000 words translationwow geld within two days, and other tasks from maple story mesosmy full-time job. On and maplestory mesoson words in the sentence have been through my hands. Iwow po was so focused on my work that I almost forget what happens outside. After the wow orearthquake hit, the people around buy Warhammer goldme have been more or less hysterical. The current Warhammer goldAftershock had tested each buy Warhammer goldof the fragile nerves. But I was immune toWarhammer gold the prevailing fever of LOTR Goldanxiety over my tight schedule. There were times wow powhen strong aftershocks are taken when wow orall others were LOTR Goldrushed out of the building, butbuy Warhammer gold I was still glued to Warhammer goldmy chair and worked on my laptop. At this time it wasbuy Warhammer gold a blessing, not to think Warhammer goldthat somewhere inLOTR gold the vicinity of the city, someone at wow geldhome was just puffing together inbuy Warhammer gold a mass of dust. In each project, I have Warhammer goldlearned different things.
I have to know aboutbuy Warhammer gold the Goth culture, learned what role the state Warhammer goldshould play in decisionwow gold making, and was given an insight into world of warcraft goldthe transformational branchlessbuy wow gold banks in other countries .Well, as I had expected, the moment the order comes after cheap wow goldthe order had. Let mewow power leveling deflated, feeling a wow powerlevelingvague kind of loss. It is time dofus kamasfor me tokamas dofus slow a bit. Looking back, I wasLord of the Rings Online Gold glad that the day I used. The only LOTRO Goldthing I felt was angry LOTR Goldabout my son. Rule No. 1: Never the work home on weekends. Therefly for fun penya were times I had thisflyff penya rule for some buy flyff goldemergency. The end of my son in the Final Fantasy XI gilhands of my husband buy cheap ffxi gilwas not a veryffxi gil good option. My little thing grew so lay for me. Hebuy Warhammer gold had all the way, heWarhammer gold could conjure up as a baby, my attention to tear me apartbuy Warhammer gold my work: groans, giggles, Gurgler, throw toys on the floor. Once my Warhammer goldeyes on him, his innocent runescape moneyface was now split into a wide smile, and he would his plump runescape goldarms for my hug. To resist such temptation, it was almost impossible. Sorry, my dear.

13. On Jul 11 2009 @ 04:29 sunzheng wrote:

cheap wow power leveling
buy wow gold
my wow power leveling
cheapest wow gold
CHEAP wow power leveling
BUY wow gold
MY rs gold
good wow power leveling
CHEAPEST lotro gold
cheap aion gold
buy wow gold
my wow gold
cheapest wow gold

14. On Jul 14 2009 @ 03:52 guest wrote:

buy wow gold
my wow power leveling
buy wow gold
good wow power leveling
BUY wow gold
my wow power leveling
CHEAP rs gold
cheap wow power leveling
CHEAPEST lotro gold
MY aion gold
buy wow gold
cheap wow gold
CHEAPEST wow gold

16. On Jan 05 2010 @ 14:26 uggbaileybutton wrote:

bailey button uggs

-ugg boots cheap

ugg boots uk

ugg classic

17. On Jan 10 2010 @ 09:28 ugg14785 wrote:

Ugg Boots,also called Ug or Ugg boots,are nowadays one of the most popular boots.They existed already in 1930's and became popular in 1960's when Australian surfers found out,that they can warm their feet after coming out from cold water.They have everything you need-comfort and warmth.You will never be cold in those boots because 100% sheepskin will warm you even in the coldest days.The natural thermal properties of sheepskin make possible that Ugg Boots will warm you in the winter but in the summer your feet will not be wet.It is true that Ugg is shorter from ugly,but if you know even little bit about fashion you will know that Ugg boots are not ugly.We can see famous people like Pamela Anderson or Kate Hudson wearing Ugg Boots.

Nowadays we have new improved Ugg boots for sale.You can get them for anybody.We have women boots,children boots,slippers and casuals.

Our UGG Australia Boots are all authentic.Their properties and features as below:

*In cold temperatures,the fleece works as an insulating layer of warmth and keeps the warmth of body heat inside of the boot.
*In the heat,the wool fibers keep the air circulating; thus keeping your fee dry and pulling the perspiration away from your skin.Sheepskin also contains lanolin,which moisturizes your feet when worn barefoot.
*ugg boots have reinforced toes,which are double stitched and extra durable heels.
*feature a natural,thick fleece on a removable in-sole for arch support.
*The sole is usually durable in most terrain,lightweight and provides traction as well.
welcome to www.bootscardy.com

18. On Jan 10 2010 @ 09:29 ugg14785 wrote:

We have been exporter of UGG Australia Boots for many years,our product are all authentic.Welcome to buy any boots of them in our website,we charge the shipping fee.
We just take 7 days to deliver the products to your door.

As everyone knows,UGG Australia Boots in australia, and many other countries as well, ugg boots also ug or uggs are a style of footwear that has been used generically for well over a hundred years.Everywhere you go now you find that the ugg boot has become the latest fashion trend.

Our UGG Australia Boots are all with top quality:

*100% authentic sheepskin for unrivalled comfort
*flexible molded EVA outsole
*Insole features a genuine sheepskin sockliner that naturally wicks away moisture and keeps feet dry
*Wool blend knit uppers with suede heel guards
*Approximate Shaft Height (Uncuffed): 14.5"
*By UGG Australia;Imported.

  welcome to www.bootsdept.com

19. On Jan 10 2010 @ 09:30 ugg14785 wrote:

The original ugg boots is not a brand name but an age old sheepskin boots generic term for this style of australian-made sheepskin boot. in Aussie slang, the ug name is short for “ugly.” in terms of comfort, however, the ug boot is a thing of beauty.Ugg boots are a popular brand of boot for women,and children.just as the chairman of australian ugg said, australian ugg is a good choice. once wearing it, you will be reluctant to take it off and be fascinated by its originality, reliability and extremely luxurious comfort. this is the art brought by boots. ugg boots make young beautiful girls and handsome boys very confident.

Our website have many fashion styels of UGG Boots for women and children.

We provide many advantages as below:
*free shipping
*hidden costs
*professional customers service
*secure processing,plus
*we dont hassle you on returns.if you dont like what youve received, simply return it!

UGG Boots must be you best choice!
welcome to www.bootshotsale.com

20. On Jan 10 2010 @ 09:30 ugg14785 wrote:

When heard of winter, cold may come in your mind at once.if you are ready for the coming of winter,you should never be afraid of it.it is not difficult for us that if you protect your feet well,you will fell warm and comfortable.so you should get several shoes help you spend the cold winter.UGG Boots can be done.for many individuals,ugg boots provide the perfect insulation and comfort for the winter months.ugg boots are both warm and comfortable.these two factors are extremely important,no matter what amount of time you are going to be spending out in the weather.ugg boots are made out of a material that is water resistant, meaning that no water,and no cold air,can get into your boots.they will keep in the warmth of your feet,because of their outer shell and their inner linings. once you slip your feet into a pair of these boots,they will be warm and toasty until it is time to take them off.you will be able to take advantage of the great warmth that ugg boots offer.

Welcome to buy UGG Boots in our website,we offer the UGG Australia boots are with top quality:
*features genuine twin-face sheepskin for refreshing comfort
*feature a soft foam insole covered with genuine sheepskin
*have a molded EVA light and flexible outsole designed for amazing comfort with every step.
*you can enjoy free shipping worldwide in our website.
*1 week delivery to your door
*sometimes you can get a special discount from our company by email


Our customers are always satisfied with such kind of UGG Boots and our high service!

welcome to www.dressugg.com

21. On Jan 10 2010 @ 09:31 ugg14785 wrote:

Legend has it that "ugg" is short for "ugly" - so, "ugg boots" apparently meant "ugly boots." For decades, "ugg" was generic term used for sheepskin boots made in Australia.The word was so commonplace that it was found in Australian dictionaries, and ugg boots were also known as "ug" or "ugh" boots. But in the United States, when people refer to "UGG boots," they're usually talking about the boots made by Deckers Outdoor Corporation, the parent company of "UGG Australia."So if you're traveling the world and talking about footwear, it's good to know that when the term "ugg boot" is used, it could be referring to an Australian-made sheepskin boot, or a popular brand name boot.

We sell authentic UGG Boots in our website for many year.We offer the best service and favourable price.People all aound the world buy our products do not pay for the shipping,we charge it!

Our UGG Boots have the advantages below:
* 100% authentic sheepskin for unrivalled comfort
* genuine twin-face sheepskin for refreshing comfort
* have a molded EVA light and flexible outsole designed for amazing comfort with every step.
*You can wear them up or style them folded down

Welcome to buy UGG Boots in our website,we offer the UGG Australia boots are all with top quality!
welcome to www.e-uggs.com

22. On Jan 10 2010 @ 09:32 ugg14785 wrote:

what's the main point of the boots?the answer is to keep your feet warm.If you by one pair of boots put them on,especially in winter,you'll feel very tenderness and comfortable.they can make your feet warm.and youll find its really fashionable.you can tie-in each kind of clothes with them and still looks beautifull.

The ugg boots will definitely make you noticeable in a fashion-conscious crowd,and more importantly,is the fact that these boots are indeed quite comfortable to wear. these boots have been popular with swimmers and surfers since the 1970s and are regularly worn by surfers in california.the design of the boot with its sheepskin results in considerable thermostatic benefits.


We sell real UGG Australia Boots in our website.You must be satisfied with our UGG Boots when you receive your order.The UGG Boots you get will have these advatages:
*100% authentic sheepskin for unrivalled comfort
*a durable molded rubber outsole.
*The wrap around lace feature adds a fashionable touch with wooden beads at the end
*A removable and replaceable sheepskin insole gives extra comfort and warmth.
*Insole is made of sheepskin,latex.
welcome to  www.famousuggs.com

23. On Jan 10 2010 @ 09:32 ugg14785 wrote:

Sheepskin and ugg boots are a casual type of boot. Ugg boots are exceptionally warm and are great for cold weather (up to -30 degrees Fahrenheit)If you are looking for warmth while trudging around the house or the city, a sheepskin or ugg boot will be ideal.For girls and women, ugg boots look fantastic with tight-legged jeans tucked into them, or with short skirts paired with opaque tights or bare legs. For guys, ugg boots work great with jeans, and give a very casual, or rugged look, depending on the jeans or the shirt you wear with your ugg boots.

Do you have a pair of UGG Boots?If not,you must will buy a piar in our website.As we offer the best sevice and favourable price.what's more,we charge the shipping fee.So,you just need to pay the fee of boots,and will receive our UGG boots in one week.It is very easy to have your own UGG Boots.Come on!

Our UGG Boots are all with top quality:
*features genuine twin-face sheepskin
*our signature UGG woven label
*feature a soft foam insole covered with genuine sheepskin
*have a molded EVA light and flexible outsole designed for refreshing comfort with every step
welcome to www.findugg.com

24. On Jan 10 2010 @ 09:33 ugg14785 wrote:

Everywhere you go now you find that the ugg boot has become the latest fashion new arrival cheap trend. now days it seems that you can not walk pass any window display of any shoe or fashion clothing store with seeing a pair of these trendy boots in them. it does not matter where ever you are in the world you will find ugg boots. these boots are both hot and trendy and certainly do not need to be worn in cold weather only. many people have found, that one pair of ugg boots is not enough.

We have been seller of UGG Boots for many years.Our customers are satisfied with our products as we offer the real UGG Australia Boots:
*100% authentic sheepskin for unrivalled comfort
*soft genuine sheepskin heel padding
*cushioning insoleEverywhere you go now you find that the ugg boot has become the latest fashion new arrival cheap trend. now days it seems that you can not walk pass any window display of any shoe or fashion clothing store with seeing a pair of these trendy boots in them. it does not matter where ever you are in the world you will find ugg boots. these boots are both hot and trendy and certainly do not need to be worn in cold weather only. many people have found, that one pair of ugg boots is not enough.

We have been seller of UGG Boots for many years.Our customers are satisfied with our products as we offer the real UGG Australia Boots:
*100% authentic sheepskin for unrivalled comfort
*soft genuine sheepskin heel padding
*cushioning insole,flexible fabric-trimmed midsole.
*Lightweight molded EVA traction outsole
*Free shipping
*One week to your door
*If you dont like what youve received, simply return it!
welcome to  www.fineugg.com,flexible fabric-trimmed midsole.
*Lightweight molded EVA traction outsole
*Free shipping
*One week to your door
*If you dont like what youve received, simply return it!
welcome to  www.fineugg.com

Add a new comment

Name:
Password: (leave empty for anonymous comment)
 
View formatting tags Comment: