Reading ‘Javascript The good Parts’ from Crocksford, I’ve been in a quest to write some efficient, readable and reusable JavaScript code.
That’s all I aim, and particularly like the Object’s properties being public.
That being said, is there any particular problem or point of improvement to this code?
( function(){
window.App = {}
// define uma pessoa normal
App.Person = function(name){
this.name = name || "anon"
this.iq = 100
this.fortune_number = Math.floor(Math.random()*100)
}
App.Person.prototype.sayName = function() {
return (this.name+"!")
}
App.Person.prototype.sayIQ = function() {
return (this.iq)
}
// define um genio da humanidade
App.Genius = function(name) {
App.Person.call( this, name )
this.iq = 9000
};
// inherits All methods from Pessoa
App.Genius.prototype = App.Person.prototype
App.Genius.prototype.solveNP = function() {
return "eureka!"
};
})()
var p = new App.Person('Jon')
console.log( "A Person:", p.sayName(), p.fortune_number, p.sayIQ() )
//-> A Person: Jon! 10 100
var g = new App.Genius( 'Eugenios' )
console.log( "A Genious:", g.sayName(), g.fortune_number, g.sayIQ(), g.solveNP() )
//-> A Genious: Eugenios! 7 9000 eureka!
I’m particularly unsure if this line App.Genius.prototype = App.Person.prototype is good, because I usually see prototyping after some new instance, like in Mozilla Guide
There is no true inheritance in your code. You HAVE TO extend the prototype chain in order to have true (prototypal) inheritance.
This has the side-effect of executing the Parent constructor which can be bad in some cases (for instance if the constructor expects any parameters). You should use the following bit to do the inheritance.