3
\$\begingroup\$

What do you say about the code structure below? This is one of the recommended ways of writing JS code in my education.

What is the pros and cons with writing code this way? Can you recommend any better and maybe more elegant ways of writing code?

var DESKTOP = DESKTOP || {};
DESKTOP.Init = DESKTOP.Init || {};
DESKTOP.Windows = DESKTOP.Windows || {};
DESKTOP.desktop = DESKTOP.desktop || {};

DESKTOP.Windows = function(width, height){
    this.width = width;
    this.height = height;
};

DESKTOP.Windows.prototype.buildWindow = function(){
    // code here...
};

DESKTOP.Windows.prototype.showMenu = function(text){
    // code here...
};


DESKTOP.Windows.bgChange = function(width, height){
    DESKTOP.Windows.call(this, width, height);

    this.content = 'the content';
    this.title =  'the title'
};

DESKTOP.Windows.bgChange.prototype = new DESKTOP.Windows();

DESKTOP.Windows.bgChange.prototype.loadImages = function(){
    // code here...
};


DESKTOP.Desktop = function(){
    // code here...
};

and so on...

\$\endgroup\$

1 Answer 1

4
\$\begingroup\$

Oh gosh... that looks horrible, whoever is teaching you has no idea of JS whatsoever.

I'll give you a quick start on "good" structure.

A bit on naming:

UPPERCASE = Constant
UpperCamelCase = Class
everythingElse = method / function / variable

Write a helper for defining namespaces, everything else will become unmaintainable soon.

namespace('Desktop.Windows');

Desktop.Init = function() {

};

Desktop.Windows.prototype = {

    buildWindow: function() {


    },

    showMenu: function() {

    }

};

No idea what bgChange is supposed to be, a sub-class?

If you want to have "sub class" behavior:

namespace('foo.Base');
foo.Base = function(a, b, c) {

};

// Write your self a generic extend(a, b, c...) function which copies the values from b, c... onto a
extend(foo.prototype, {

    show: function() {

    },

    other: function() {

    }

});


namespace('foo.Extended');
foo.Extended = function(a, b, c, d) {

    foo.Base.call(this, a, b, c);
    // use d

};

extend(extended.prototype, foo.prototype, {

    // "Overwrite"
    show: function() {
        foo.Base.prototype.show.call(this, ...); // "super call"
    }


});
\$\endgroup\$
2
  • \$\begingroup\$ Is it really possible to write: "namespace('Desktop.Windows');" ? \$\endgroup\$ Commented Jan 9, 2012 at 20:38
  • \$\begingroup\$ If you provide a function called "namespace" which abstracts away the creation, sure ;) \$\endgroup\$
    – Ivo Wetzel
    Commented Jan 11, 2012 at 20:29

Not the answer you're looking for? Browse other questions tagged or ask your own question.