我正在编写一些JavaScript类(旧学校,不使用ES2015/ES6,我不想使用Babel或其他转换器),并且我有一个继承另一个,覆盖其中一个父方法。对原型类使用对象文字
所以,我有我的初步App.Hello
类:
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);
}
}
的然后我App.Yo
类从它继承:
// 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);
}
}
但是因为我使用对象字面结构我改写的原型App.Yo
当我通过它constructor
和sayHello
方法后设置Object.create
。所以我没有从App.Hello
继承sayGoodby方法
1.我怎样才能解决这个问题,但使用文字结构?
我知道我可能只是这样做:
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);
}
但我想保持字面结构,我的课将会有很多在他们不同的方法。所以想保持它的漂亮和整洁。
2.是否可以将整个类嵌套为文字?那么构造函数也嵌套为文字的一部分吗?
例如
App.Hello = function(args) {
this.name = args.name;
}
和
App.Yo = function(args) {
App.Hello.call(this, args);
}