/    Sign up×
Community /Pin to ProfileBookmark

OOP Javascript

Hi all I come from C,C++,Visual Basic,Java,Perl,PHP and then now to Javascript. My knowledge of Javascript is still at those late 90’s era where it is used for simple scripting purposes.

Recently due to the need to learn AJAX coding, I discover Javascript has changed ALOT!!! In fact I find the different kind of syntax to create objects in Javascript mind-boggling!!! I have below questions to ask.

  • 1.

    Is there a Interface concept in Javascript ?

  • 2.

    Is there a abstract class concept in Javascript ?

  • 3.

    Is there final static variables concept in Javascript ?

  • 4.

    Are there private, protected, public fields/methods concept in Javascript ?

  • 5.

    Is there sub-classing and inheritance concept in Javascript ?

  • 6.

    Does Javascript support multiple inheritance ?

  • 7.

    Does Javascript support template like C++ ?

  • For each of the questions above I would appreciate some code snippets as I am trying to learn the OOP Javascript syntax which I believe is very counter-intuitive to a developer whose background is from those classical OOP languages like C++ and Java.

    Thanks.

    to post a comment
    JavaScript

    15 Comments(s)

    Copy linkTweet thisAlerts:
    @KorMar 24.2010 — Even JavaScript is an object oriented language, it does not use [I]classes[/I] - at least not the present largely used version, which is JavaScript 1.2 to 1.5. For the moment, JavaScript is a [I]prototype based language[/I]. That means the inheritance is performed via a process of cloning existing objects - on using so called [I]prototypes[/I]. In other words JavaScript uses the [I]delegation[/I] (from object to its prototype), not the inheritance. We may say that Javascript is able to simulate many class-based features but on using prototypes. Javascript simply uses objects, not classes and instances. [I]Everything[/I] is an object in javascript: variables, references, functions, methods...

    More about JavaScript as a prototype based language:

    https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Class-Based_vs._Prototype-Based_Languages

    http://www.crockford.com/javascript/inheritance.html

    For this reason (but not only) JavaScript is a slow language (about 100 times slower than C++, for instance)

    Still, the new proposal version (JavaScript 2.0) promises to implemented classes, which might transform JavaScript into a hybrid language.

    JavaScript is a [I]client-side language[/I] which was meant to create/change/remove the [B]elements[/B] of a web document, their [B]attributes[/B] or attributes' [B]values[/B]. In order to do that, JavaScript uses [B]methods[/B]. Methods are nested in [B]functions[/B]. In JavaScript functions are treated like [I]first-class objects[/I]. Functions are triggered by [B]events[/B], following the user's [B]actions[/B].

    As a [I]client-side[/I] language, JavaScript can not store/write data. That means when the session is changed, all the modifies it could have done on a page are lost, except if data is previously sent to a data base via a server-side application. There might be also the cookie technique, but that is a relative solution, as user might not accept cookies and, further more, the "memory" of a cookie is drastically limited.

    JavaScript is a stable language. There are standards:

    [B]The language: ECMAScript

    The Object Model: DOM[/B]


    Unfortunately, even there were made consistent progresses in the last years, there is not even a single browser which is able to follow [I]entirely all[/I] the standards and recommendations, thus the coders must learn/test these differences between the main browsers as well. There are historical reasons for that, among which: the war between IE and Netscape, the war between IE and Mozilla, the war between IE and the rest of the world :rolleyes: . We may say that JavaScript is the forsaken child of a romantic but indolent deceased father (Netscape - LiveScript) and a shrew voracious step-mother (IE - JScript), under the wardship, now, of a bunch of several giddy uncles (W3C - World Wide Web Consortium) ?

    So that, for the moment, JavaScript has an [I]ideal[/I] common interface paradigm, but not in [I]real-life[/I]

    But this is a common problem for other client-side languages (markup - HTML/XHTML or stylesheet - CSS) as well. Here are some good compatibility compare tables:

    http://www.quirksmode.org/compatibility.html

    Several good online tutorials:

    http://www.w3schools.com/js/default.asp

    http://www.howtocreate.co.uk/tutorials/javascript/introduction

    http://www.quirksmode.org/js/contents.html
    Copy linkTweet thisAlerts:
    @rnd_meMar 24.2010 — first off, let me start by saying that a lot of these terms can be ambiguous.

    certain language implement certain features and patterns in different ways.

    i find it hard to say that anything has anything because the thing means different things to different people.

    I don't come from a C++/OOP background, that might be painfully clear below, so bear with me. i'm not sure javascript does 100% of the things classical languages do, or if they are 100% the same as language x,y, or z.

    that said, i do know a little bit about oop, and a lot about javascript.

    I'll try to answer as best I can for what i think you're trying to accomplish.

    this type of analysis is just begging for a flame war...

    for example, I don't care if javascript doesn't have "official" classes, so long as it is capable of the things "real" classes do.


    [B][COLOR="Red"]1. Is there a Interface concept in Javascript ?[/COLOR][/B]

    no, i don't think so. interfaces are like a type, a user-defined type right?

    in one sense, javascript has no abstract or composite types, because there's no way to define a type without making an instance.

    on the other hand, the DOM provides several standard collections of methods and properties. you can duplicate, delete, mute, and link methods to/from other objects. as a last resort, you can iterate and duplicate to get the job done.

    i might say that constructors and their byproducts are types to themselves. In fact, using a constructor function binds an invisible (non-enumerable) property called constructor to the object. this lets you determine what "type" of object it is.

    For soft/literal objects, it's all about duck-typing and coercion in javascript.


    [B][COLOR="Red"]2. Is there a abstract class concept in Javascript ?[/COLOR][/B]

    since objects are soft, and types are dynamic, there's no need for such a thing. you might say they're all abstract. until the next version of ecmaScript comes out, there's no way to finalize objects.

    [B][COLOR="Red"]3. Is there final static variables concept in Javascript ?[/COLOR][/B]

    one thing at a time.

    final: a firefox+webkit extension, [I]const [/I]is local:
    [CODE]function check(){
    const y={a:1};
    y.a=5;
    return y;
    }
    alert(check().a)//===5[/CODE]

    but consts aren't static, they are automatic...

    you can use assessors to mimic the effect, but on a technical level the answer is no. that said, private variables are safe inside their functions as long as inner-function code don't alter them.

    static:

    yes, though not how you'd expect. there's a few ways to do static-y things in javascript.

    javascript can use closure to make things vanish from one perspective, but remain alive from another. you can wrap a function around your code to conceal and preserve variables for other functions:
    [CODE](function(){
    var x=123;
    showX=function(){alert(x);}
    }());

    x=99;
    showX();//123[/CODE]

    in that example, the "123" x will be around as long as the function showX is around. there is no way to alter or delete that specific x, though if it becomes un-reachable it will get garbage-collected.

    objects, including functions, can hold properties. typically, functions are globals, and are thus reachable from anywhere and permanent.

    properties of globals are also permanent and global, so you don't need to pollute the global namespace with several functions to keep them around.

    as a result, the pattern i consider the best static is using function names to hold them:

    [CODE]function count(){
    return ++count.total;
    }; count.total=0;

    alert([ count(), count(), count(), count(), count() ]);
    //shows: 1,2,3,4,5[/CODE]



    at the cost of a defining a default, you can define statics internally, which has the added benefit of working in methods:

    [CODE]var o={
    counter:
    function count(){
    count.total=count.total||0
    return ++count.total;
    }
    };

    alert([ o.counter(), o.counter(), o.counter(),
    o.counter(), o.counter(), "Total:", o.counter.total ]);

    //shows: 1,2,3,4,5,Total:,5[/CODE]

    note the distinct internal and external function names, that's important in javascript...



    [B][COLOR="Red"]4. Are there private, protected, public fields/methods concept in Javascript ?[/COLOR][/B]

    there are:

    private, public, static, prototype, and privileged methods in all browsers.

    private, public, static, and privileged GET properties in all browsers.

    private, public, static, and privileged SET properties in IE8+, all recent others.

    about privileged methods

    [CODE]
    function Demo(){
    function getter(){return private;} //private
    var private=555;
    this.public=123;
    function hi(){alert("hi");} // private
    this.hello=function(){alert("hello");} // public
    this.getPrivate=function(){alert(private);} // privileged method
    this.invited={valueOf: getter, toString: getter}; // privileged property
    Demo.lastBuilt=this; // "static"
    }
    Demo.prototype.proto=function(){alert(this.public);} //prototype method

    var obj=new Demo();
    [/CODE]

    after running, obj will have the following direct properties:

    - public, hello, getPrivate, and invited.

    in addition, the following are not self-properties, but are available:

    - o.proto, Demo.lastBuilt



    [B][COLOR="Red"]5. Is there sub-classing and inheritance concept in Javascript ?[/COLOR][/B]

    yes. objects, including arrays and functions are accessed by reference, making for dead-simple inheritance/linking from anywhere to anywhere else (withing the same window at least).

    you don't even need constructors for this type of inheritance:
    [CODE]var ray=[1,2,3];
    var dupe=ray;

    dupe[1]="Fred";
    ray[3]=false;

    alert(ray); //shows: 1,Fred,3,false[/CODE]


    there's also [I]with[/I] to temporarily implement the property pool of an object as lexical scope. function closure can seal in the link created by with, making a permanent bond:
    [CODE]var obj={a:1, b:2, c:3};

    with(obj){
    function adder(){
    alert(a+b+c);
    }
    }//end with

    adder()//===6
    obj.b=10;
    adder()//===14[/CODE]



    see the next answer for a more classical inheritance pattern using constructors.

    remember that primitives can propagate, but remain frozen; you'll have to use assessor functions. javascript (since 1999) includes two native but read-only assessors for all objects: [I]toString [/I]and [I]valueOf[/I]. IE8 and later versions of all the other browsers can do GET and SET assessors, which provides a way to do primitive inheritance.


    [B][COLOR="Red"]6. Does Javascript support multiple inheritance ?[/COLOR][/B]

    to some extent. you have no explicit control over joins; the closest property always wins.

    example:
    [CODE]
    function Life(){
    this.type="life"
    this.alive=true;
    }
    function Animal(){
    this.type="animal";
    this.age=0;
    this.die=function(){this.alive=false;}
    }
    function Person(){
    this.type="human";
    this.birthday=(new Date).toLocaleDateString();
    }
    //join the constructors by linking thier prototypes:
    Animal.prototype=new Life;
    Person.prototype=new Animal;


    var me= new Person, props=[];
    for(property in me){
    props.push( property +":t"+ me[ property ] );
    }

    alert(props.join("n"));

    /* shows:
    type: human
    birthday: Wednesday, March 24, 2010
    age: 0
    die: function () {
    this.alive = false;
    }
    alive: true */
    [/CODE]



    [B][COLOR="Red"]7. Does Javascript support template like C++ ?[/COLOR][/B]

    all functions can do something like it:

    [CODE]
    //making "new " prefix optional:
    function Constructor(args){
    if(this.Array==Array){return new Constructor(args);}
    this.arg=args;
    }
    var x= new Constructor("fred");//==={ arg="fred"}
    var y= Constructor("fred");//==={ arg="fred"}

    //overloading/flexible args
    function el(id){
    if(id.nodeName){return id;} //quack
    if(id.splice){return id.map(el);}//quack
    return el._ts[id]||(el._ts[id]=document.getElementById(id));
    }; el._ts={};
    [/CODE]


    the el function recreates document.getElementById() when used in the same way.

    but, el can also accept live elements instead of a string id.

    this means that el([I]elm[/I]) is guaranteed to give me an element or nothing, even if i don't know what [I]elm[/I] is at design time.

    it also takes arrays of ids or elements or both mixed.

    note that the el function above requires Array.map.

    that's built into non-IE browsers and is available as a seamless drop-in for IE.


    --------
    whew, does that answer your question?


    take your shoes off, get comfortable with soft objects and weak types, and enjoy the ride.

    I'll bet that in a large room of programmers, one of them will disagree with everything i said above.
    Copy linkTweet thisAlerts:
    @KorMar 24.2010 — 
    I'll bet that in a large room of programmers, one of them will disagree with everything i said above.[/QUOTE]

    Not really.? I do agree with most of. Except that, in my opinion, what you are naming [I]inheritance[/I] is in fact [I]delegation[/I], as JavaScript does not really use the concept of classes and instances. Or, better say, there is no firm structural distinction between objects, functions, methods and instances. JavaScript creates, uses, clones and destroys only [I]objects[/I], as everything is an object.
    Copy linkTweet thisAlerts:
    @sohguanhauthorMar 24.2010 — Thanks a lot for everyone for your contribution. I guess I gotta do a big mindset shift to understand Javascript "OO" concept. Will ask in this forum once I got problem again.
    Copy linkTweet thisAlerts:
    @rnd_meMar 24.2010 — 
    For this reason (but not only) JavaScript is a slow language (about 100 times slower than C++, for instance)[/QUOTE]


    i used to say the same thing, but i don't think that's still true.

    Near C Performance for RIAs with Next Generation Mozilla JavaScript Engine (2008)

    even IE8, sandbagged by tester including .js file download in run time, was only 20-30X slower in this roundup.

    also consider that chrome is easily 15X faster than IE8: try it yorself

    so, even if IE6 was 100X slower than C++, at worst, chrome would be no more than 7X slower than C++.


    the apps i wrote in javascript run the same code a lot faster today than they did a few years back, even on the same computer.

    it took no effort from my end to make my apps faster, the browsers did it for me. thanks.

    also consider that for complex projects, C++'s speed depends a lot on the compiler used to build the app. once you make your executable, you're stuck with that level of performance. if a smarter compiler comes along, you'll have to rebuild.

    yes, certain low-level task will always be faster in C++; that's a mathematical fact.

    but on a complex app, if the javascipt engine can cheat and the compiler didn't or couldn't, things could get interesting. given the pace of JIT and tracemonkey development, i would not be surprised to see, under the right conditions, javascript BEAT C++ compiled with an undergrad-level home-made compiler. it could happen in a couple short years.

    IE9 will use the often-vacant 2nd core or a multi-core CPU as a dedicated javascript compiler. that might be interesting.

    i also can't wait to see what happens wehn firefox starts using Chrome-like JIT in combination with it's own tracing engine!


    perhaps we all need to reconsider the 100X rule.

    right now, it's probably closer to 10x, or 30x for IE.
    Copy linkTweet thisAlerts:
    @KorMar 24.2010 — 
    perhaps we all need to reconsider the 100X rule.
    [/QUOTE]

    Agree. But when I am thinking of C#, (not C++), I wonder...?
    Copy linkTweet thisAlerts:
    @svidgenMar 24.2010 — Agree. But when I am thinking of C#, (not C++), I wonder...?[/QUOTE]

    ... Does C# produce faster binaries than C++?
    Copy linkTweet thisAlerts:
    @KorMar 24.2010 — ... Does C# produce faster binaries than C++?[/QUOTE]
    I don't think so. When we are talking about simple loops for instance, C++ should be faster. But when we are talking about complex C# applications, they [I]should run[/I] faster as they are compiled [I]twice[/I] (second time at the .NET Framework level).

    By the way, [B]sohguanh[/B], there is another aspect: JavaScript is an [I]interpreted[/I] language, not a [I]compiled[/I] one.
    Copy linkTweet thisAlerts:
    @sohguanhauthorMar 25.2010 — By the way, [B]sohguanh[/B], there is another aspect: JavaScript is an [I]interpreted[/I] language, not a [I]compiled[/I] one.[/QUOTE]

    Hi Mr Kor I know of cuz. Since my working career began, I have been using C,C++,Visual Basic then to Java, Perl and PHP.

    The reason why I need to learn Javascript is for my software developer career advancement. I do not see using C++ to do AJAX coding do you?

    Therefore, depending on the task on hand, we will use the appropriate language for it. For AJAX, Javascript and maybe .NET (but I am not a M$ lover so go figure ? is the way to go.
    Copy linkTweet thisAlerts:
    @KorMar 25.2010 — Well, when entering JavaScript coming from C languages , I guess you must do that as you would learn an almost complete new language. The JavaScript paradigm is different, the structure is different... in a word: the final aim of JavaScript is different. Only the base syntax resembles, now and then.

    The final aim is important to understand this language. I will repeat myself:

    [I]JavaScript is a client-side language which was meant to create/change/remove the elements of a web document, their attributes or attributes' values. In order to do that, JavaScript uses methods. Methods are nested in functions. In JavaScript functions are treated like first-class objects. Functions are triggered by events, following the user's actions. [/I]

    Regarding AJAX: AJAX is nothing but a technique, not a language. AJAX is based on 3 foundation stones: 1. the request object (XMLHttpRequest or, for IE <=7: ActiveX ) , 2. JavaScript, 3 (optional) XML, If the request is not for an XML file, you need an extra server-side application (written in PHP, or ASP, or Pearl, or Java, or whichever...) to handle the request to and from a DB.

    Not a bright idea to use .NET (probably you mean ASP .NET) for websites. php/MySQL is the winner pair, for the moment.
    Copy linkTweet thisAlerts:
    @svidgenMar 25.2010 — Regarding AJAX: AJAX is nothing but a technique, not a language. AJAX is based on 3 foundation stones: 1. the request object (XMLHttpRequest or, for IE <=7: ActiveX ) , 2. JavaScript, 3 (optional) XML, If the request is not for an XML file, you need an extra server-side application (written in PHP, or ASP, or Pearl, or Java, or whichever...) to handle the request to and from a DB.[/QUOTE]

    You can actually avoid XMLHttpRequest if you don't need to POST any data. Dynamically adding script tags is probably the most cross-browser compatible and efficient "AJAX" technique. You can even perform cross-site requests in this manner if you trust your sources ...

    Not a bright idea to use .NET (probably you mean ASP .NET) for websites. php/MySQL is the winner pair, for the moment. [/QUOTE]

    Visual Studio provides some very neat options for AJAX though--even with my severely limited knowledge writing web apps with Visual Studio, I can say that publishing web services (SOAP services) couldn't be easier than writing them in C#. You basically just mark your public methods, and Visual Studio will not only keep the WSDL up to date "on its own," but also generates more human-readable documentation to go with it. Very nice.

    And with Visual Studio, I imagine you could create fairly efficient web services in C++ ...

    If you want to use C++ in a linux/unix/bsd environment, you'll want to figure out how to write apache modules. You could write binaries that work as CGI's, but CGI's are horribly inefficient. (The fire up a new process for [B]every[/B] HTTP request that hits them.)

    PHP is probably the most [I]efficient[/I] and affordable option. (Though you can get VS [I]Express[/I] editions for free, you still have to pay for the Windows OS to serve the site from.)
    Copy linkTweet thisAlerts:
    @sohguanhauthorMar 26.2010 — If you want to use C++ in a linux/unix/bsd environment, you'll want to figure out how to write apache modules. You could write binaries that work as CGI's, but CGI's are horribly inefficient. (The fire up a new process for [B]every[/B] HTTP request that hits them.)

    PHP is probably the most [I]efficient[/I] and affordable option. (Though you can get VS [I]Express[/I] editions for free, you still have to pay for the Windows OS to serve the site from.)[/QUOTE]


    Hi I have discovered an alternative not using CGI. Similar in concept to PHP is the classic Apache Mod_Perl. It is a Perl interpreter embedded inside the Web Server. This avoid the CGI overhead.

    Thanks.
    Copy linkTweet thisAlerts:
    @svidgenMar 26.2010 — Yup ... If you really want to go the Perl route, there's always mod_perl.
    Copy linkTweet thisAlerts:
    @sohguanhauthorMar 30.2010 — Hi all after a week or so of intensive reading, I have hopefully (?) capture and learn the Javascript OOP syntax. I know ppl will say learning syntax is trivial but coming from the C,C++,Java background, the Javascript OOP syntax require some mindset changes.

    I hope to share with other fellow programmers that are school-ed OOP in the classical way an easier route to Javascript OOP. Start off would be it's syntax.

    Please note there maybe errors in the attachment. Feel free to comment on it.

    Thanks.

    [upl-file uuid=2157f51b-2b16-442d-ad52-c5db8f3c0636 size=6kB]Notes.txt[/upl-file]
    Copy linkTweet thisAlerts:
    @rnd_meMar 31.2010 — Hi all after a week or so of intensive reading, I have hopefully (?) capture and learn the Javascript OOP syntax. I know ppl will say learning syntax is trivial but coming from the C,C++,Java background, the Javascript OOP syntax require some mindset changes.
    [/QUOTE]

    if people say javascript syntax is trivial, they are mistaken. learning C is trivial: it's logical, well-documented, and predictable. Javascript on the other hand has little good documentation, is not extensively taught in school (yet), and behaves differently in different runtimes, which are constantly changing and evolving.

    given the limited number of keywords in javascript, the subtle and undocumented combination of those terms is extremely important, and not often intuitive. i think these facts conspire to make javascript, as of late, particularly hard to learn, given its supposed simplicity and over-arching relevancy.

    the c++ style oop approach in javascript is just not that spectactular, and goes against javascript's grain. the good news is that javascript has, quite literally, a more modern approach. everyone would love to simply use their trusted, hard-earned skills in this new place, but they don't work, or at least not very well or quickly.

    i have probably realized more about JavaScript by studying lisp than reading javascript books. lisp is a fairly well-documented alternate approach to computing that sheds a lot of light on the way javascript works internally.

    the procedural side of javascript is about the same as C, but once you get into OOP, your wheel suddenly becomes a ball.
    ×

    Success!

    Help @sohguanh spread the word by sharing this article on Twitter...

    Tweet This
    Sign in
    Forgot password?
    Sign in with TwitchSign in with GithubCreate Account
    about: ({
    version: 0.1.9 BETA 6.2,
    whats_new: community page,
    up_next: more Davinci•003 tasks,
    coming_soon: events calendar,
    social: @webDeveloperHQ
    });

    legal: ({
    terms: of use,
    privacy: policy
    });
    changelog: (
    version: 0.1.9,
    notes: added community page

    version: 0.1.8,
    notes: added Davinci•003

    version: 0.1.7,
    notes: upvote answers to bounties

    version: 0.1.6,
    notes: article editor refresh
    )...
    recent_tips: (
    tipper: @meenaratha,
    tipped: article
    amount: 1000 SATS,

    tipper: @meenaratha,
    tipped: article
    amount: 1000 SATS,

    tipper: @AriseFacilitySolutions09,
    tipped: article
    amount: 1000 SATS,
    )...