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 1 of 2 12 LastLast
Results 1 to 15 of 20
  1. #1
    Regular Coder
    Join Date
    Mar 2003
    Posts
    241
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Constructor problem with arrays?

    Hallo all,
    I am trying to do my very first OOP- javascript and I am now stuck, why will this not work ?

    function PP(width,height,oobjects,status,debug) {
    this.width = width;
    this.height = height;
    this.steps = oobjects.length; // <<CAUSES THE ERROR
    this.status = status;
    this.debug = debug;
    }

    function callPP() {
    var test = new PP();
    test.width = 150;
    test.height = 15;
    test.steps = new Array("test1", "test2");
    test.status = false;
    test.debug = false;

    document.write(test.steps);
    }

    I could do a 'dirty' workaround but I'd rather not, and I happen to be curious what's wrong with this code too

    Thanks for any help.

  • #2
    Regular Coder ellisd5's Avatar
    Join Date
    Jun 2002
    Location
    Uk
    Posts
    160
    Thanks
    5
    Thanked 0 Times in 0 Posts
    what are you passing into your function for 'oobjects'

  • #3
    Regular Coder
    Join Date
    Mar 2003
    Posts
    241
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Usually it will be images in an array, but I'm thinking of maybe adding other files too, wav-files for example.

    I'm trying to do a OO-progressbar, with some options, but I want to start out with a basic version first, then maybe add a few nice features.

    thanks for your fast reply btw.

  • #4
    Regular Coder ellisd5's Avatar
    Join Date
    Jun 2002
    Location
    Uk
    Posts
    160
    Thanks
    5
    Thanked 0 Times in 0 Posts
    So are you passing in the auctual whole Array, or just a single value.

    If the codes not to big, post up the array and the part of the code that calls the function

  • #5
    Regular Coder
    Join Date
    Mar 2003
    Posts
    241
    Thanks
    0
    Thanked 0 Times in 0 Posts
    The whole array will be put on the bold line later on, I just used this to test around:

    function callPP() {
    var test = new PP();
    test.width = 150;
    test.height = 15;
    test.steps = new Array("test1", "test2");
    test.status = false;
    test.debug = false;

    document.write(test.steps);
    }

  • #6
    Regular Coder
    Join Date
    Nov 2002
    Posts
    596
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Time to back up a bit and review some basics....

    function callPP() {
    var test = new PP();
    .....

    This calls your constructor PP(). It's just a function - albeit one with a specialized purpose - and it immediately executes the following statements:

    this.width = width;
    this.height = height;
    this.steps = oobjects.length;

    The first two run - in a poorly-conceived manner ('initializing' properties to 'undefined' rather than an actual value); but, since you've passed no oobjects object (array), you're asking the constructor to look up a property of 'undefined'. You'll need to either pass your constructor the necessary arguments to initialize the properties, or set 'placeholder' values (an empty array, in this case), or add some code that allows the constructor to analyze how it's being called, and set up accordingly. Try entering 'object-oriented JavaScript' in google, and click around for a while...

  • #7
    Senior Coder
    Join Date
    Jun 2002
    Location
    frankfurt, german banana republic
    Posts
    1,848
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Another tip if you want to improve your OO design a little: Use seperate methods to set/get the properties of your object. Those methods are (surprise, surprise!) conveniently refered to as getter and setter methods. They allow you to maintain and control the state of the object, and you can restrict the access to internal variables of the object.

    If you combine that with the approach to make object variables private, you have a very good control of what the user of an object may alter and what not. Just some suggestions, ask for clarification if my post was to obscure.
    De gustibus non est disputandum.

  • #8
    Regular Coder
    Join Date
    Apr 2003
    Location
    Atlanta, GA
    Posts
    487
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Considering that there is no such thing as a true private or protected variable in javascript, OO design can only get so close before it's a waste of code.

    Getters and setters are great for Java, smalltalk, coldfusion components, C++, any other kind of OO software or software tool which recognizes restrictions inside objects; in Javascript it's usually just as safe to name your "public" variables normally and prefix the "private" variables with an underscore or what-not.

    Anything more is either practice for server-side or desktop applications, or programmatic masturbation.

  • #9
    Senior Coder
    Join Date
    Jun 2002
    Location
    frankfurt, german banana republic
    Posts
    1,848
    Thanks
    0
    Thanked 0 Times in 0 Posts
    You can use closures to restrict the visibility of variables in an object:

    Code:
    function Obj() {
    	var foo = '';
    	
    	this.setFoo = function(value) {
    		foo = value;
    	}
    	
    	this.getFoo = function() {
    		return foo;
    	}
    }
    
    var test = new Obj();
    test.setFoo('hello world');
    
    alert(test.getFoo());
    alert(test.foo); // <- Error: "foo is not defined"
    Programmatic masturbation, eh? I'd say it's a rather useful concept. Just because it is not very common shouldn't mean that OOP principles should be softened when doing something more complex in JavaScript. But it's you choice, the nice thing in a language like JavaScript is that you can decide which route you take. YMMV.

    http://www.crockford.com/javascript/private.html
    De gustibus non est disputandum.

  • #10
    Regular Coder
    Join Date
    Apr 2003
    Location
    Atlanta, GA
    Posts
    487
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Yet again, I find myself tasting shoe. Let me apologize for my flippant attitude, especially what with my admission that my knowledge of javascript really isn't up to par with my knowledge of my primary language (ColdFusion - please don't laugh at me).

    Mordred, these revelations about javascript understanding private and protected properties and methods do make it feel more like java, but where does this leave room for the prototype, other than extending its methods? Should I create the properties in the constructor using var, then make getters and setters for each of them? Again, I feel this may be a waste of code, but it would be good to do at least for the variables which shouldn't be changed outside the object's methods, but do I then need getters and setters for each of these private vars, to be called inside the public methods?

    So many questions, so many threads.

  • #11
    Regular Coder
    Join Date
    Aug 2002
    Location
    São Paulo, Brazil
    Posts
    367
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Choopernickel:

    It may seem like a waste of code using those getters and setters. But a good reason to do so is that they preserve the interface of the object. The only thing you need to worry about when using the object is to call it's methods. If the properties needs some formating or validation it's done inside the getters/setters.
    Ex;
    Code:
    function foo(v){
        var value;
        this.setValue=function(v){
            (isNaN(v) ? value = -1 : value = v);
        }
        this.getValue=function(){
             (value==-1 ? return "N/A" : return value);
        }
        this.setValue(v);
    }
    
    // Usage:
    var f=new foo(2);
    var val=f.getValue();
    Without them:

    Code:
    function foo(v){
        this.value=(isNaN(v) ? -1 : v);
    }
    
    // Usage:
    var f=new foo(2);
    var val=f.value;
    if (val==-1){
        val = "N/A";
    }
    When you (or the client) later decides that it's should not be "N/A" but " - ", you have to look for all the places in your code where you used the value to change it.

    Maybe a poor example, but you get the idea?
    /Daniel

  • #12
    Regular Coder
    Join Date
    Apr 2003
    Location
    Atlanta, GA
    Posts
    487
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Okay, yeah, that makes sense Danne, so I understand why it makes sense to use setters and getters for a) variables that contain output data, and b) variables which have no need to be exposed.

    What about setting variables, though? Imagine foo is an object, and bar is a switchable setting. Why bother with this:
    Code:
    function foo() {
        // ...
        var bar = false;
        this.setBar = function (bool) {
            bar = bool;
        }
        this.getBar = function () {
            return bool;
        }
    }
    foo.prototype.aMethod(splorp) {
        if (this.getBar()) {
            doSomething();
        }
    }
    myFoo = new foo();
    foo.setBar(true);
    foo.aMethod();
    when this will suffice
    Code:
    function foo() {
        // ...
    }
    foo.prototype.bar = false;
    foo.prototype.aMethod(splorp) {
        if (this.bar) {
            doSomething();
        }
    }
    myFoo = new foo();
    foo.bar = true;
    foo.aMethod();
    ?

    Why even bother with the prototype at all, when all of this can be coded with nested functions which access public and private variables all on their own? Is it really just a matter of style or personal preference? What kind of underlying benefits exist to the more OO approach of private variables and "priviledged" (not really protected) methods? Performance? Certainly not file size or code weight. Any?

    So you know, I really do appreciate and am enjoying this conversation.

  • #13
    Regular Coder
    Join Date
    Aug 2002
    Location
    São Paulo, Brazil
    Posts
    367
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Objectorientation may seem like more code in the beginning, but using it means reusable code, which means less coding. Once you have created the objects, all you need to do is use them. If you find a bug within an object, make sure the interface is intact.

    When to use to use public properties and when not to? Avoid public properties when working with objects that you want to reuse.
    This is probably a matter of choice, though. I know I use way too many public properties, and I usually have to suffer for it...

    The downside of objectorientation may be performance and more time to plan the objects before the actual coding (which is actually a good thing, but may seem boring at first).

    When you get in to inheritance is when you really start to love it..
    /Daniel

  • #14
    Regular Coder
    Join Date
    Apr 2003
    Location
    Atlanta, GA
    Posts
    487
    Thanks
    0
    Thanked 0 Times in 0 Posts
    That's the thing, though. I have a wonderful, pretty-much-OO script that is called via one line of instantiation code. It uses public properties and methods, and nothing private or priviledged. It weighs in at 142 lines of code (5.5kb), with nothing stored in the global scope except the constructor.

    I went through and "privatized" it, making all the properties private and adding getters&setters, modifying all the code, etc. Its instantiation is the exact same, but now it weighs in at 204 lines (6.5kb), again with nothing stored in the global scope except the constructor. It works exactly the same in every way, except changing the settings.

    I can't detect any changes in performance, but I haven't set up any timers or testers. I can't say whether it actually is better packaged, but it doesn't seem it. It's no more reusable with private variables than it is with public variables. The only difference I can see is that now I could create an API document, which would be beneficial to other developers. Documentation? Bah!

    However, it's time to post it in the "Post A Javascript" forum.

  • #15
    Senior Coder
    Join Date
    Jun 2002
    Location
    near Oswestry
    Posts
    4,508
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Encapsulation - if you're making an API for other people to use, there's a risk of variable and function-name conflicts when you don't know what else will be running. OO avoids that, because you only need one or a small number of container objects.
    "Why bother with accessibility? ... Because deep down you know that the web is attractive to people who aren't exactly like you." - Joe Clark


  •  
    Page 1 of 2 12 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
    •