I'm writing some JavaScript classes (old school and NOT using ES2015/ES6 and I don't want to use Babel or other transpilers) and I have one that inherits from the other, overriding one of the parent methods.
So I have my initial App.Hello
class:
var App = {};
App.Hello = function(args) {
this.name = args.name;
}
App.Hello.prototype = {
constructor: App.Hello,
sayHello: function() {
console.log('Hello, ' + this.name);
},
sayGoodbye: function() {
console.log('Goodbye, ', this.name);
}
}
An then my App.Yo
class which inherits from it:
// inherits from App.Hello
App.Yo = function(args) {
App.Hello.call(this, args);
}
App.Yo.prototype = Object.create(App.Hello.prototype);
App.Yo.prototype = { // want to combine this with above!
constructor: App.Yo,
sayHello: function() {
console.log('Yo, ', this.name);
}
}
However because I'm using Object literal structure I overwrite the prototype of App.Yo
when I pass it the constructor
and sayHello
methods after setting the Object.create
. So I don't inherit the sayGoodby method from App.Hello
1. How can I get around this but using literal structure?
I know I could just do:
App.Yo.prototype = Object.create(App.Hello.prototype);
App.Yo.prototype.constructor = App.Yo;
App.Yo.prototype.sayHello = function sayHello() {
console.log('Yo, ', this.name);
}
But I want to keep the literal structure as my classes are going to have a lot of different methods in them. So want to keep it nice and tidy.
2. Is it possible to nest the complete class as a literal? So have the constructors as well nested as part of a literal?
e.g.
App.Hello = function(args) {
this.name = args.name;
}
and
App.Yo = function(args) {
App.Hello.call(this, args);
}