Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Page 2 of 4 FirstFirst 1234 LastLast
Results 16 to 30 of 51

Thread: OOP JavaScript

  1. #16
    Regular Coder
    Join Date
    Oct 2003
    Location
    SC
    Posts
    936
    Thanks
    0
    Thanked 0 Times in 0 Posts
    why wont this work?
    watch('cat1.name', cat1.talk())

  2. #17
    Regular Coder
    Join Date
    Nov 2003
    Location
    Code Heaven
    Posts
    129
    Thanks
    0
    Thanked 0 Times in 0 Posts
    When prototyping all instances of the object will share that property/methd u add/change,but if u change a prop/method for an object instance,only that instance is affected...

  3. #18
    Senior Coder
    Join Date
    Aug 2002
    Posts
    3,467
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Javascript inheritance is both clunky and rarely useful. I've written lots and lots of OOP javascript, and I agree with mordred: composition and aggregation are much more useful facilities of OO when talking javascript. I'm not saying JS inheritence is never right, I'm just saying it very rarely is. The types of tasks we use Javascript for just don't need it.

    I think one of the biggest benefits that OO JS offers has been mentioned, but not highlighted yet by this thread: multiple instances.

    Just search around - you're bound to find many people having problems trying to "run the same script more than once on the same page". Since coding objects provides encapsulation, we can instantiate as many instances as we like of the same script, not to mention the benefits when running multiple scripts of various natures simultaneously..
    My Site | fValidate | My Brainbench | MSDN | Gecko | xBrowser DOM | PHP | Ars | PVP
    “Minds are like parachutes. They don't work unless they are open”
    “Maturity is simply knowing when to not be immature”

  4. #19
    Master Coder
    Join Date
    Feb 2003
    Location
    Umeå, Sweden
    Posts
    5,575
    Thanks
    0
    Thanked 83 Times in 74 Posts
    Originally posted by mordred
    liorean, I don't know why you brought up inheritance. You don't need to use inheritance if you have better, more fitting alternatives, and yet your app may qualify as a true OOP app nevertheless. Often, inheritance is overused and better refactored as composition/aggregation. Remember that inheritance breaks encapsulation.

    Originally posted by beetle
    Javascript inheritance is both clunky and rarely useful. I've written lots and lots of OOP javascript, and I agree with mordred: composition and aggregation are much more useful facilities of OO when talking javascript. I'm not saying JS inheritence is never right, I'm just saying it very rarely is. The types of tasks we use Javascript for just don't need it.

    I think one of the biggest benefits that OO JS offers has been mentioned, but not highlighted yet by this thread: multiple instances.
    Going to answer to both those at once, because I feel they are both related, and that some of my message here is getting lost: the only feature difference between object oriented and object based systems is type/object inheritance. Granted, I've not said it straight out, but the comparisons should have made the fact clear. JavaScript objects are not fixed, as they are in most compiled languages. This leads to that you can dynamically change objects and prototypes, which means that instead of using subclasses you manipulate your objects and instances. This makes a flat inheritance tree much more suited for JavaScript than a deep inheritance tree. But this flattening the inheritance tree also leads to that most of your objects are actually first level in the inheritance tree, and in those cases there is no benefit to using object orientation instead of an object based system. Aggregation and composition can be made as easily from an object based system, true encapsulation is provided by closures, and the code is cleaner.

    Which lead me to the second part of what Peter said - in JavaScript inheritance very rarely is the right thing.


    I said in my post above, "for every task the tools best equiped for the purpose". By which I did not mean that you should avoid using object orientation in all cases. What I meant was that you should not use object orientation if inheritance is not a required feature. Nor did I mean that you should continue to pollute the global namespace by coding procedurally. I meant that you should use the programming method best suited for the purpose, and that in most cases, object based, functional style programming is better than any other style you might happen to use. Concentrate on what task you want your JavaScript to perform, not what structures you use in performing said task.

    Oh. just before I forget it: Multiple instances can as easily be achieved by object based systems as object oriented. Unless you use a closure to that effect, they will not inherit, but again, inheritance is not a very useful feature in JavaScript.



    Well, let's return to another thing - why I think my cookies library is a really good example of why object orientation does not make things more readable or understandable. Here's the pretty printed, nice names version of my cookies library:
    Code:
    var cookie={
        Get:function(name){
            var
                re=new RegExp(name+'=([^;]*);?','gi'),
                result=re.exec(document.cookie)||[];
                return unescape(result.length>1?
                    result[1]:
                    null);
        },
        Set:function(name, value, expirationTime, path, domain, secure){
            var
                time=new Date;
            if(e)
                time.setTime(time.getTime()+(expirationTime*8.64e7));
            document.cookie=name+
                '='+
                escape(value)+
                '; '+
                (!expirationTime?
                    '':
                    '; expires='+time.toUTCString())+
                (!path?
                    '':
                    '; path='+path)+
                (!domain?
                    '':
                    '; domain='+domain)+
                (!secure?
                    '':
                    '; secure');
        },
        Del:function(name, path, domain){
            var
                value=this.Get(name);
            document.cookie=name+
                '='+
                (!path?
                    '':
                    '; path='+path)+
                (!domain?
                    '':
                    '; domain='+domain)+
                '; expires=Thu, 01-Jan-70 00:00:01 GMT';
            return value;
        },
        Sup:function(){
            this.Set('c',true);
            return this.Del('c');
        }
    };
    and here's an object oriented cookies handling library (they aren't doing exactly the same thing, so there's some difference there, but I still think they pretty much show what I mean)
    Code:
    function Cookies(){
        var
            oCookies={},
            aRawCookies=document.cookie.split(/;/g),
            i=aRawCookies.length,
            aTemp;
    
        function Cookie(name, value){
            this.name=name;
            this.toString=function(){
                return value;
            };
        }
        
        while(i-->0){
            aTemp=aRawCookies[i].split(/=/g);
            oCookies[aTemp[0]]=new Cookie(aTemp[0],aTemp[1]);
        }
        
        this.munch=function(name){
            return (typeof oCookies[name]!='undefined')?
                oCookies[name]:
                false;
        }
        
        this.bake=function(name, value, expirationTime, path, domain, secure){
            oCookies[name]=new Cookie(name, value);
            document.cookie=name+
                '='+
                escape(value)+
                '; '+
                (!expirationTime?
                    '':
                    '; expires='+time.toUTCString())+
                (!path?
                    '':
                    '; path='+path)+
                (!domain?
                    '':
                    '; domain='+domain)+
                (!secure?
                    '':
                    '; secure');
        }
        this.trash=function(name, path, domain){
            var
                value=this.munch(name);
            document.cookie=name+
                '='+
                (!path?
                    '':
                    '; path='+path)+
                (!domain?
                    '':
                    '; domain='+domain)+
                '; expires=Thu, 01-Jan-70 00:00:01 GMT';
            if(typeof oCookies[name]!='undefined')
                delete oCookies[name];
            return value;
        }
    
        this.bake('cookiesSupport', true);
        this.support=this.trash('cookiesSupport');
    }
    
    var cookiejar=new Cookies;
    Last edited by liorean; 02-16-2004 at 12:09 AM.
    liorean <[lio@wg]>
    Articles: RegEx evolt wsabstract , Named Arguments
    Useful Threads: JavaScript Docs & Refs, FAQ - HTML & CSS Docs, FAQ - XML Doc & Refs
    Moz: JavaScript DOM Interfaces MSDN: JScript DHTML KDE: KJS KHTML Opera: Standards

  5. #20
    Senior Coder
    Join Date
    Aug 2002
    Posts
    3,467
    Thanks
    0
    Thanked 0 Times in 0 Posts
    I think there's a semantic confusion here, liorean. I think I'm assuming correctly when I say just about everyone equates "object orientation" and "object based" when talking about javascript.
    My Site | fValidate | My Brainbench | MSDN | Gecko | xBrowser DOM | PHP | Ars | PVP
    “Minds are like parachutes. They don't work unless they are open”
    “Maturity is simply knowing when to not be immature”

  6. #21
    Master Coder
    Join Date
    Feb 2003
    Location
    Umeå, Sweden
    Posts
    5,575
    Thanks
    0
    Thanked 83 Times in 74 Posts
    Yes, there certainly is. And because of that I'm going to ask this:
    - What makes one of the code snippets object oriented and the other object based?
    - What is the technical difference between cookiejar and cookie, if you ignore how their members work?
    liorean <[lio@wg]>
    Articles: RegEx evolt wsabstract , Named Arguments
    Useful Threads: JavaScript Docs & Refs, FAQ - HTML & CSS Docs, FAQ - XML Doc & Refs
    Moz: JavaScript DOM Interfaces MSDN: JScript DHTML KDE: KJS KHTML Opera: Standards

  7. #22
    Senior Coder
    Join Date
    Aug 2002
    Posts
    3,467
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Because one is a constructor and the other is not -- it's a static object.
    My Site | fValidate | My Brainbench | MSDN | Gecko | xBrowser DOM | PHP | Ars | PVP
    “Minds are like parachutes. They don't work unless they are open”
    “Maturity is simply knowing when to not be immature”

  8. #23
    Master Coder
    Join Date
    Feb 2003
    Location
    Umeå, Sweden
    Posts
    5,575
    Thanks
    0
    Thanked 83 Times in 74 Posts
    Well, not quite. Cookies and Cookie are the constructors. I was talking about cookiejar (from the second code sample) and cookie (from the first code sample).

    (Besides, I didn't intend that question for you to reply on, I know you understand what I mean here. I was trying to get one of those that argued against what I said before to give a view on it.)
    liorean <[lio@wg]>
    Articles: RegEx evolt wsabstract , Named Arguments
    Useful Threads: JavaScript Docs & Refs, FAQ - HTML & CSS Docs, FAQ - XML Doc & Refs
    Moz: JavaScript DOM Interfaces MSDN: JScript DHTML KDE: KJS KHTML Opera: Standards

  9. #24
    Regular Coder
    Join Date
    Jun 2002
    Location
    Round Rock, Texas
    Posts
    443
    Thanks
    0
    Thanked 0 Times in 0 Posts
    I just re-read the majority of this thread; as I was googling for "javascript inheritance" in preparation for a project. Which leads me to a situation which looks like a good candidate for using inheritance..

    How about when manipulating data from a normalized database? One might aruge that composition could/will fill the bill, but inheritance seems to be a natural fit for the data. Much of the data seems to have a "is a" relationship vis-a-vis a "has a" relationship - although there may be some of that too. My "spidey sense" is telling me that inheritance will be a good way to hold the data, structured, in javascript - nicely mirroring the (intended) data design.

    We have "components" of different "types". All component has common attributes, like name, price, an ID. But the different types carry very different sets of attrubutes. And there are many different types and likely to be more in the future. Additionally certain types have interdependancies, or perhaps a different set of rules for the same dependancy. Make sense? Kinda fuzzy maybe, being so generic here.

    So waddya think?

  10. #25
    Regular Coder
    Join Date
    Nov 2003
    Location
    Code Heaven
    Posts
    129
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Not really much to do with the general subject,but I remember asking some time ago how to create a static property or metod,such as the Math object has,also the Date object has a few static methods if I'm not mistaken...
    Well I got the asnwer:

    function Object(param1,param2)
    {
    //Code here...
    }

    Object.staticProp=5;
    Object.staticMethod=function(){...} ;



    &Stuff...

  11. #26
    Regular Coder
    Join Date
    Jul 2002
    Posts
    698
    Thanks
    0
    Thanked 0 Times in 0 Posts
    composition is not the same as inheritance.

    composits can see each public interfaces either one way or both ways.

    in inheritance the child can see its parent's public,protected interface.

  12. #27
    Regular Coder
    Join Date
    Jun 2002
    Location
    Round Rock, Texas
    Posts
    443
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by Code Wizard
    Not really much to do with the general subject,but I remember asking some time ago how to create a static property or metod,such as the Math object has,also the Date object has a few static methods if I'm not mistaken...
    Well I got the asnwer:

    function Object(param1,param2)
    {
    //Code here...
    }

    Object.staticProp=5;
    Object.staticMethod=function(){...} ;
    C.W.
    Are you saying that because "staticProp" is a property of the Object object that it is unchangeable? Couldn't I do this?
    Code:
    var ObjectofMyDesire = new Object
    ObjectofMyDesire.staticProp = 20;

  13. #28
    Regular Coder
    Join Date
    Nov 2003
    Location
    Code Heaven
    Posts
    129
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Sorry haven't coded anything in quite a while(my recent post was just a reminiscence) but I'll give it a shot...altough I could be wrong...

    Code:
    var ObjectofMyDesire = new Object
    ObjectofMyDesire.staticProp = 20;
    The code u wrote would create a new empty object,for which u could then assign properties(and methods).
    If we could write it's constructor function,it would probably look like this(also,I believe the (empty)Object object is only implemented in MS JScript):
    Code:
    function Object()
    {
    return this;
    }
    The fact is that this piece of code would assign a prop to an instance,not to the constructor:
    Code:
    ObjectofMyDesire.staticProp = 20;
    To assign a static property(or method),you have to assign the value(or function) to the object constructor.
    Hope I made that clear enough

  14. #29
    Regular Coder
    Join Date
    Jun 2002
    Location
    Round Rock, Texas
    Posts
    443
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Sorry, I'm confusing myself. I was thinking 'constant' not static. But static in the java sense means there is only one instance, and it's available to all objects of that class. JS does not have classes, so as I understand the Javascript object model, JS does not have a static-like feature.

    OK loriean is going to chime in here any minute now!

  15. #30
    Regular Coder
    Join Date
    Nov 2003
    Location
    Code Heaven
    Posts
    129
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Well,static in teh JScript sense,means that the particular property(or method) is accesible only from the object's constructor.
    Just think at the Math object's methods and props - u never create a Math object on your own,you just use it's (static) methods and properties.
    Also,looking at the Date object - you can make new instances of it,but I suggest you to look at it's parse() method...
    There is nu such thing as "unchangeable" in JScript,as it doesn't have features that allow you to protect your data from being changed.
    There IS a techinique that's called a Closure(I suggest you google it up) that seems to allow some data hiding,but still,you won't find any information on this in any recent book.


 
Page 2 of 4 FirstFirst 1234 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •