Discussion Locked

Build more powerful JavaScript code

0 helpful
2 replies
Closed to new repliesThis discussion is closed. It stays readable, but it takes no new replies.

This week's Web Development Zone e-newsletter explains how you can build more powerful JavaScript code using classes. Do you program in JavaScript? If not, what programming language(s) do you primarily work in? Are the tips in this e-newsletter useful to you?

If you aren't subscribed to the free Web Development Zone e-newsletter, you can automatically subscribe to this e-newsletter by pasting the following URL into your browser:
http://nl.com.com/MiniFormHandler?brand=builder&subs_channel=bldr_front_door&list_id=e055&tag=fb

* Please delete any extra spaces that appear when you paste this URL into your browser.

2 replies

by builder

Nice, short overview.

I use OO JS by preference, including class inheritance when appropriate. (Though I've done little with class inheritance in a while, as I've not done any large applications in JS in several years.)

I find it easier to manage and understand the code, if a little more verbose,
to place the methods *outside* the constructor. For example:

    function CObject() { 
        this.count = 0;
        this.number = 1;

        this.sayCount = CO_sayCount;
        this.addCount = CO_addCount; 
    } 

    function CO_addCount() {
        this.count++; 
    }; 

    function CO_sayCount() {
        alert(this.count); 
    };

    var myObject1 = new CObject(); 
    var myObject2 = new CObject(); 
    myObject1.sayCount(); 
    myObject2.sayCount(); 
    myObject1.addCount(); 
    myObject1.sayCount(); 
    myObject2.sayCount(); 

See my other reply for comments on inheritance.

- SamR

by builder

You mention that using prototype allows class inheritance (if in a primitive form). You don't say how. It's simply by assigning a new prototype object of the parent class to the new class' prototype instance:

function myClass() {
this.newMethod = MC_newMethod;
}
myObject.prototype = new parentClass();
myObject.prototype.attribute1 = "default value";

Any new methods defined in myClass then extend or override those in the prototype.

The default values for the prototype may then be assigned to it directly, as shown above.

By default (i.e., if no specific prototype object is assigned) the class prototype is an Object.

- SamR

This discussion is closed to new replies.