I'm a bit confused about what is the right way to write object
oriented code in JS. The majority of the projects
on the web are using constructor functions coupled with prototypes,
but I don't really understand why.
Why nobody does the inheritance like in the sample code below? Besides
the fact that __proto__ is non-standard and Object.create() is pretty
new, is there anything wrong with this code? For some reason it feels
to me like the most natural approach to inheritance in JS.
//
// Human object
//
var Human = {
// Init
init: function() {
console.log('Initializing Human object');
},
// Properties and methods
legs: 2,
hands: 2,
eyes: 2,
isMammal: true,
canTalk: true,
sayHello: function() {
alert('hello');
}
}
//
// Man object, inherits from Human
//
var Man = {
// Parent
__proto__: Human,
// Init
init: function() {
Human.init.call(this);
console.log('initilizing Man object');
return this;
},
// Properties and methods
gender: 'male',
}
//
// Man instance
//
var john = Object.create(Man).init();
--
To view archived discussions from the original JSMentors Mailman list:
http://www.mail-archive.com/[email protected]/
To search via a non-Google archive, visit here:
http://www.mail-archive.com/[email protected]/
To unsubscribe from this group, send email to
[email protected]