Javascript Orientado a Objeto

Javascript Orientado a Objeto

by Angelo Rogério Rubin

HTML

<h1 id="result"></h1>

CSS

body {
    font-family: Verdana, Arial;
    font-size: 0.4em;
}

JavaScript

// Construtor (semelhante a uma classe)
var Gadget = function(name, color) {
    this.name = name;
    this.color = color;
    this.whatAreYou = function(){
        return 'I am a ' + this.color + ' ' + this.name;
    }
};

// Adicionando propriedades e metodos 
Gadget.prototype = {
    price: 100,
    rating: 3,
    getInfo: function() {
        return 'Rating: ' + this.rating + ', price: ' + this.price;
    }
};

// Adicionando um novo metodo ao prototype
Gadget.prototype.get = function(what) {
    return this[what];
};

// Instância de Gadget
var newtoy = new Gadget('barbie','pink');

/** 
 * Loop for in para verificar se a propriedade/metodo 
 * pertence ao objeto ou ao prototype
*/
for (var prop in newtoy) {
    if (newtoy.hasOwnProperty(prop)) {
        // console.log(prop + '=' + newtoy[prop]);
    }
}

// console.log(newtoy.propertyIsEnumerable('name'));

// Objeto
var monkey = {
    hair: true,
    feeds: 'bananas',
    breathes: 'air'
};

// Construtor
function Human() {}
Human.prototype = monkey;

// Protótipo
/*
Human.prototype = {
    lastname : "Rubin",
    fullname : function(){
        return this.name +" "+this.lastname;
    }
};
*/

var result = document.getElementById('result');

var george = new Human('George');
// console.log(monkey.isPrototypeOf(george));

// console.log(result.innerHTML = angelo.name +" "+angelo.lastname);

// for (var i in cliente) {
    // console.log(i + '=' + angelo[i]);
// }

// result.innerHTML = cliente.fullname();

var developer = new Human();
developer.feeds = 'pizza';
developer.hacks = 'javascript';

// result.innerHTML = george.__proto__.breathes;

Array.prototype.inArray = function(needle) {
    for (var i = 0, len = this.length; i < len; i++) {
        if (this[i] === needle) {
            return true;
        }
    }
    return false;
}

a = ['caneta','lapis','borracha'];
// console.log(a.inArray('caneta'));

String.prototype.reverse = function(){
    return...