Last Updated: February 25, 2016
·
960
· glitchmr

JavaScript classes template

// Constructor
function Animal(name) {
    this.name = name
}

// Method
Animal.prototype.move = function (meters) {
    alert(this.name + " moved " + meters + "m.")
}

// Constructor which inherits Animal
function Snake() {
    // super constructor
    Animal.apply(this, arguments)
}
Snake.prototype = new Animal

// Method
Snake.prototype.move = function (meters) {
    alert("Slithering...")
    // super
    Animal.prototype.move.apply(this, arguments)
}

// Create new Snake and move it
new Snake('Sammy the Python').move(5)

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Related Tags
#javascript
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside