I'm looking at ways to apply Object Oriented in JavaScript. I noticed that there are several ways to do Inheritance in JavaScript. I did the one I found simple and worked. But is it really within the standards? is correct?
Follow the Code:
function humano(){
var nome;
this.pensar = function(){
return "Estou pensando";
}
}
function animal(){
this.comer = function(){
return "Vou COMER!";
}
}
humano.prototype = new animal();
var pablo = new humano();
pablo.nome = "Pablo";
console.log(pablo.pensar());
console.log(pablo.comer());
console.log("Meu nome é " + pablo.nome);
Studying more, now I came up with the following code for Inheritance, would this be an advanced form of inheritance in JavaScript? (obs .: The extra properties created were to test the passing of properties by inheritance)
var obj = {};
var coisa = {
nome: 'Rafael',
idade: '35'
};
obj.y = 55;
Object.defineProperty(obj,'x',{value: 1, writable: false, enumerable: false, configurable: true});
Object.defineProperty(obj,'x',{get: function(){ return obj.y}});
Object.defineProperty(Object.prototype,"extend",{
writable: true,
enumerable: false,
configurable: true,
value: function(o){
var names = Object.getOwnPropertyNames(o);
for(var i = 0; i < names.length; i++ ){
if(names[i] in this) continue;
var desc = Object.getOwnPropertyDescriptor(o,names[i]);
Object.defineProperty(this,names[i],desc);
}
}
})
obj.extend(coisa);
coisa.extend(obj);
What is the best way? Thanks