Skip to the posts
Buffalo's neighborhood journals since 2003 🍀 Patrick Spicy Devil Logan🌭 Sahlen🥨 Weber Spank🥟 Pierogi🐸 Scaj🍺 Labatt Utica Pink Cherio❄️ Snow Murder

paul’s journal

Javascript Prototypes Part II

· · 🌡️ 59°F

Here is a good example I wrote of javascript prototypes that extend other objects. @paul #4369 was part one and both were in reference to @zobar #59

[box]<html>
<body>
<script type="text/javascript">
/*create a sound object for making sounds*/
sound = function(noise){
    this.setNoise(noise);
}

/*add new prototype to output the noise */
sound.prototype = {
    /*set the noise echoed on sound.out)*/
    setNoise : function(noise){
        this.noise = noise || 'plain sound';
    },
    
    /*output the noise*/
    out : function(numTimes){
        var noise ='"';
        for(x=0;x<numTimes;x++){
            noise += this.noise;
            if(x<numTimes-1){ noise +=', ';}
        }
        return noise+'!"';
    }
}

/*create a animal object for making animals that make sounds*/
animal = function(name, noise){
    this.setName(name);
    this.vocals = new sound(noise);
}

animal.prototype = {

    /*set the name of the animal*/
    setName : function(name){
        this.name = name || 'another animal';
    },
    
    /*prototype to wrap sound.out*/
    talk : function(times){
        alert(this.name +" said "+this.vocals.out(times));
    },
    
    /*prototype to wrap sound.setNoise*/
    changeVocals : function(noise){
        mySquirrel.vocals.setNoise(noise);
    }
    
}
/*instantiate an animal ( a squirrel that barks) and make it talk */
mySquirrel = new animal('squirrelio', 'bark');
mySquirrel.talk(3);
mySquirrel.changeVocals('ruff');
mySquirrel.talk(4);
</script>
</body>
</html>
[/box]

A lot of people have come up with different methods for dealing with inheritance. Here is one page that explains it and here is another that abstracts it a bit.

Once you are into the prototyping system you can make your own system to make extending and inheriting easier.

268 words

💬 0 comments

💬 Write a comment