DZone Refcards - OOP JS

Object Type Definition

by Denise Nepraunig

JavaScript

// DZone Refcards - OOP JavaScript
// Object Type Definition

function MyType() {
    if (!(this instanceof MyType)) {
        throw new Error("Constructor cannot be called as function");
    }
}

var myInstance = new MyType();
try {
    MyType(); // will throw an error
} catch (e) {
    console.log(e.message);
}

// instance members
// instance members are created with the this keyword,
// prototpye, constructor, closure or Object.defineProperty

function Cat (name) {
    var voice = "Meow";
    this.name = name;
}

Cat.prototype.eat = function() {
    return "Omnomnom";
};

Cat.prototpye.say = function() {
    return voice;
};