Thursday, April 22, 2010

Easy Breezy Javascript OOP

Javascript does not support classical OOP. Instead it supports prototypal inheritance. It seems that everybody still wants to use the classical OOP pattern though and I don't really blame them. I use it all the time in my own projects and I see it used in many of the libraries and frameworks out there. Some people think that classical OOP has no place in Javascript, but I and many others respectfully disagree.

Despite the numerous tutorials on the web, many people still ask what is the proper way to do classical OOP. I'm not sure if the issue is the quality of the tutorials or the myriad of ways to simulate classes. In any case, I feel that there is room for one more quick tutorial. I do not claim this way to be the "proper" way, but I do feel that it is a "good" way. Many people and libraries/frameworks use this pattern or something very close to it

Classes and the Constructor

Defining a class and it's constructor function is easy. It looks like this:

// create a class called Animal
var Animal = function(name, age) { 
    // assign the passed-in arguments to instance members
    this.name = name; 
    this.age = age;
};

Using this class is also easy:

// create an instance and assign it to the pet variable
var pet = new Animal("Spot", 2);

Instance Methods

To add an instance method, you want to use the prototype property. It looks like this:

// create an instance method called "sayHello"
Animal.prototype.sayHello = function() {
    // access instance members using the "this" keyword
    return this.name + " doesn't speak.";
};

To use an instance method, you can simply call it on the instance:

// make the animal say hello
pet.sayHello(); // returns "Spot doesn't speak."

Static Methods

Static methods are applied to directly to the class like so:

// create a static method called "getName"
Animal.getName = function(animal) {
    // return the name of the passed-in animal
    return animal.name;
};

When using a static method, you use the class:

// call the static method
Animal.getName(pet); // returns "Spot"

Subclassing

This is usually the sticky point and where many implementations differ slightly (or not-so-slightly). Like I said, I think the way I present is a good way though. It requires one little helper function.

var extend = function(subClass, parentClass) {
    var tempFn = function() {};
    tempFn.prototype = parentClass.prototype;
    subClass.prototype = new tempFn();
    subClass.prototype.constructor = subClass;
    subClass.superclass = parentClass.prototype;
};

The what, why and how are beyond the scope of this article, but I certainly encourage you to do deeper digging if you are so inclined. Using the function is rather easy though.

// create a new class called "Dog"
var Dog = function(name, age) {
    // call the constructor of the superclass
    Dog.superclass.constructor.call(this, name, age);
};

// explicitly make Dog subclass Animal
extend(Dog, Animal);

Instance Methods

To add new instance methods, just add them to the prototype of the subclass:

// create an instance method called "bark"
Dog.prototype.bark = function() {
    return "Woof!";
};

To override instance methods, and to call superclass methods, do this:

// override the instance method called "sayHello"
Dog.prototype.sayHello = function() {
    if (this.age < 1) {
        // call the super "sayHello" method
        return Dog.superclass.sayHello.call(this);
    }
    else {
        return this.bark();
    }
}

Using instance methods on the subclass works exactly like before:

var petDog = new Dog("Spot", 2);

// make the animal say hello
petDog.sayHello(); // returns "Woof!"

That's really about it. It's simple and doesn't include many things like interfaces or private members, but it works. And that's how you do easy breezy Javascript OOP.

40 comments:

  1. 精力剤:http://www.feelkanpo.com/
    威哥王:http://xn--kwrt2jp9z.feelkanpo.com/
    威哥王:http://www.feelkanpo.com/view/415.html
    三體牛鞭:http://www.feelkanpo.com/view/812.html
    勃動力三體牛鞭:http://www.feelkanpo.com/view/812.html
    三体牛鞭:http://www.feelkanpo.com/view/812.html
    三便宝:http://www.feelkanpo.com/view/823.html
    男宝:http://www.feelkanpo.com/view/634.html
    五便宝:http://www.feelkanpo.com/view/797.html
    巨人倍増:http://www.feelkanpo.com/view/427.html
    狼1号:http://www.feelkanpo.com/view/501.html
    狼一号:http://www.feelkanpo.com/view/501.html
    蟻力神:http://www.feelkanpo.com/view/604.html
    蟻力神(第五代):http://www.feelkanpo.com/view/785.html
    新一粒神:http://www.feelkanpo.com/view/821.html
    蔵八宝:http://www.feelkanpo.com/view/820.html
    黒倍王:http://www.feelkanpo.com/view/575.html
    ru486:http://www.feelkanpo.com/view/407.html
    中絶薬RU486:http://www.feelkanpo.com/view/407.html
    縮陰膏:http://www.feelkanpo.com/view/636.html
    天天素:http://www.feelkanpo.com/view/573.html
    V26:http://www.feelkanpo.com/view/566.html
    曲美:http://www.feelkanpo.com/view/847.html
    福源春:http://www.feelkanpo.com/view/798.html
    紅蜘蛛:http://www.feelkanpo.com/view/473.html
    花痴:http://www.feelkanpo.com/view/593.html
    妖姫:http://www.feelkanpo.com/view/851.html
    淫インモラル:http://www.feelkanpo.com/view/849.html
    D10 媚薬:http://www.feelkanpo.com/view/479.html
    D10催情剤:http://www.feelkanpo.com/view/479.html
    絶對高潮:http://www.feelkanpo.com/view/561.html
    韓国痩身一号:http://www.feelkanpo.com/view/491.html
    漢方会社:http://www.kanpocom.com/
    威哥王:http://xn--kwrt2jp9z.kanpocom.com/
    威哥王:http://www.kanpocom.com/Pro/weigewang.html
    巨人倍増:http://www.kanpocom.com/pro/jurenbeiceng.html
    紅蜘蛛:http://www.kanpocom.com/Pro/hong-zhi-zhu.html
    花痴:http://www.kanpocom.com/Pro/huachi.html
    D10催情剤:http://www.kanpocom.com/pro/D10.html
    絶對高潮:http://www.kanpocom.com/Pro/juedui.html
    三便宝:http://www.kanpocom.com/pro/satibo-capsules.html
    三體牛鞭:http://www.kanpocom.com/Pro/stlb.html
    勃動力三體牛鞭:http://www.kanpocom.com/pro/stlb.html
    三体牛鞭:http://www.kanpocom.com/Pro/stlb.html
    蟻力神:http://www.kanpocom.com/pro/yilishen.html
    五便宝:http://www.kanpocom.com/Pro/wodibo-capsules.html
    狼一号:http://www.kanpocom.com/Pro/langyihao.html
    狼1号:http://www.kanpocom.com/Pro/langyihao.html
    RU486:http://www.kanpocom.com/pro/beijing-ru486.html
    消渇丸:http://www.kanpocom.com/Pro/xiaokewan.html
    天天素:http://www.kanpocom.com/pro/tiantiansu.html
    V26:http://www.kanpocom.com/Pro/V26sx.html
    韓国痩身1号:http://www.kanpocom.com/Pro/hgshs.html
    韓国痩身一号:http://www.kanpocom.com/Pro/hgshs.html
    媚薬 販売:http://www.allkanpou.com/
    花痴:http://www.xn--6qs44kv2wxulv8l.com/
    淫インモラル:http://www.allkanpou.com/product/immoral.html
    花痴:http://www.allkanpou.com/product/%E8%8A%B1%E7%97%B4.html
    威哥王:http://www.allkanpou.com/product/%E5%A8%81%E5%93%A5%E7%8E%8B.html
    巨人倍増:http://www.allkanpou.com/product/%E5%B7%A8%E4%BA%BA%E5%80%8D%E5%A2%97.html
    催情丹:http://www.allkanpou.com/product/cuiqingj.html
    媚薬:http://www.allkanpou.com/biyaku/%E5%AA%9A%E8%96%AC.html
    媚薬通販:http://www.allkanpou.com/biyaku/%E5%AA%9A%E8%96%AC.html
    女性媚薬:http://www.allkanpou.com/biyaku/%E5%A5%B3%E6%80%A7%E5%AA%9A%E8%96%AC.html
    媚薬激安:http://www.allkanpou.com/biyaku/%E5%A5%B3%E6%80%A7%E5%AA%9A%E8%96%AC.html
    媚薬カプセル:http://www.allkanpou.com/biyaku/%E5%AA%9A%E8%96%AC%E5%82%AC%E6%B7%AB.html
    淫インモラル:http://immoral.yahookanpou.com/
    妖姫:http://xn--vvsqh.yahookanpou.com/
    媚薬カプセル:http://www.yahookanpou.com/catalog/60.html
    女性用媚薬:http://www.yahookanpou.com/catalog/60.html
    威哥王:http://www.yahookanpou.com/product/weigwang.html
    巨人倍増:http://www.yahookanpou.com/product/jurenbeizenggouqi.html
    三便宝:http://www.yahookanpou.com/product/sbb.html
    壮根精華素:http://www.yahookanpou.com/product/zgjhs.html
    韓国痩身一号:http://www.yahookanpou.com/product/hgssyhmtx.html
    韓国痩身1号:http://www.yahookanpou.com/product/hgssyhmtx.html
    精力剤:http://www.yahookanpou.com/
    巨人倍増:http://www.xn--tckuez55h0fbkxjnoie3j.com/
    妊娠中絶薬:http://www.xn--fiqv0z4mai18ikui.com/
    プロコミルスプレー:http://www.xn--tckm2gc2b7djc5l.com/
    催情薬:http://www.xn--o0q550b.net/
    レビトラ:http://www.xn--fdkva1ej2834bwg0a.com/
    d10媚薬:http://www.xn--d10-hl9e441q.com/
    韓国痩身一号:http://www.xn--4gq48lkwcy40cp4z0ql.com/
    蒼蝿粉:http://www.xn--i6zw1ov9b.com/
    催情丹:http://www.xn--riq92di5x.com/
    絶對高潮:http://www.xn--wetw46b3hk0yo36dn8t.com/

    ReplyDelete
  2. It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout

    ReplyDelete
  3. Auto title advances are additionally known for its quick preparing and endorsement. To the individuals who need quick money, this advance is certainly for you. 24/7 car title loans chicago

    ReplyDelete
  4. 大人気で希少なBOY CHANELシャネル バッグをご紹介します。セレブに大人気の鉄板ブラックにゴールド金具がカッコ可愛いデザインです。ルイ ヴィトン コピー バッグ http://www.drkross.com/ 斜め掛けも出来、肩からかけてショルダーとしても2連にして短めのショルダーとしても3WAYでお持ちいただけて、使い回し抜群です!華やかな雰囲気にしてくれ、お洋服のポイントになるので、使い回しも抜群。偽物 シャネル http://www.drkross.com/buranndo-24.html サイズ感は小さめですが少しのお出かけやデート等にもオススメです。

    ReplyDelete
  5. クリスチャン ディオール コピーから大人気のメンズスウェットパンツを入荷しました。http://www.kidying.com/偽 ブランド サイトChristian Dior スウェットパンツ コピーは普段着から作業着までこなせるアイテムです。http://www.kidying.com/brand-9.htmlディオール スーパーコピーこちらのブラックスウェットロングパンツは外付けドローコードが付きます。http://qbwho.com/copy-70-c0/VIVIENNE WESTWOOD スーパー コピー

    ReplyDelete
  6. Oh my goodness! an incredible write-up dude. Many thanks Nevertheless My business is experiencing trouble with ur rss . Do not know why Cannot enroll in it. Perhaps there is anyone obtaining identical rss problem? Anyone who knows kindly respond. Thnkx web design la

    ReplyDelete
  7. books online are great, wether they are e-books or conventional hardbound and paperback books~ la web design

    ReplyDelete
  8. Hello… DropshipDragon provides dropping for quality, affordable products direct from China to your customers. Perfect for eBay sellers and website owners alike!… website tips

    ReplyDelete
  9. Thanks for posting this info. I just want to let you know that I just check out your site and I find it very interesting and informative. I can't wait to read lots of your posts. sviluppo siti web Milano

    ReplyDelete
  10.  シュプリームの実店舗は世界でも12店しかなく(そのうち6店は日本にある)、売り上げの60%はECによるものだ。http://www.kidying.com/ ブランド コピー 優良 店それが幸いし、コロナ禍にあっても売上高は1ケタ台の伸びを見せている。粗利率は最大で60%程度、営業利益率は20%以上だという。またVFCは今後5年間におけるシュプリームの年平均成長率を8~10%と見積もっているが、これは「ヴァンズ」の同12~13%より低いものの、VFC全体より高い成長率が見込まれている。なお今回の買収により、VFCは少なくとも5億ドル(約515億円)の増収となる見込みだ。 シュプリーム スニーカー コピー http://www.kidying.com/brand-190.html市場はこれを好感し、VFCの株価は9日に一時、前日比19.2%高の83.48ドル(約8598円)を付けている。

    ReplyDelete
  11. You can trust Nelson Tree Specialist for all of your tree care needs.
    tree surgery Manchester

    ReplyDelete
  12. It is very easy to understand this new thing. You can also get knowledge about lottery gambling games at http://www.decomoh.com. Find it and prove it afterwards.

    ReplyDelete
  13. Thanks for sharing.I found a lot of interesting information here. A really good post, very thankful and hopeful that you will write many more posts like this one. 스포츠토토

    ReplyDelete
  14. Right away I am ready to do my breakfast, later than having my
    breakfast coming again to read additional news. 카지노사이트

    ReplyDelete
  15. This article offers clear idea in support of the new people of blogging, that genuinely how to do running a blog. 카지노사이트

    ReplyDelete
  16. That's a really impressive new idea! casino api It touched me a lot. I would love to hear your opinion on my site. Please come to the site I run once and leave a comment. Thank you.


    ReplyDelete
  17. I have been reading your blog posts for month and its been the greatest thing I am doing in past few months. keep up the good work for sharing the information. 메이저사이트

    ReplyDelete
  18. back every day. It’s great to have a place like this. I’ll come often. Great work! 바카라사이트

    ReplyDelete
  19. Read this blog. It is always so lovely. Thankyou for all your efforts that you have put in this.

    ReplyDelete
  20. I hope you will continue to have such a great articles to share with everyone!

    ReplyDelete
  21. I read your article very impressively I want to write something like this

    ReplyDelete
  22. Nice article and explanation Keep continuing to write an article like this

    ReplyDelete
  23. Aw, this was an extremely good post. thanks. Pretty great post. Thankyou

    ReplyDelete
  24. Awesome motivating article. You put extremely accommodating data. Keep it up

    ReplyDelete
  25. Wonderful article! Keep on writing man. These are actually great ideas

    ReplyDelete
  26. Hello. This is an Impressive post. Keep on blogging. This is an excellent post

    ReplyDelete