在ES5,有一个基类,提供一个公共的API定义:扩展和覆盖JS类的私人和公共方法
var Class = function(name) {
var self = this;
var name = name;
return {
print: function() {
printDetails();
return this;
},
iAmA: function() {
console.log('I am an instance of:', self.constructor.name);
}
};
function printDetails() {
console.log('Name', name);
};
};
我如何:
延长它没有实例化它
是
Child.prototype = Class
没有new
wron G?我只想定义类和继承,而不是实例化任何类。覆盖的私有方法(并使其通过调用公共方法)
我想Child.print()调用Child.printDetails(),而不是Class.printDetails( )。
继承类的公共API不重新声明它
我可以
return new Class(name)
从儿童,但我不会被称为我的新儿童方法(类方法被调用,而不是)向api中添加一个方法而不用全部重新声明
我不知道这是否可能,但我的目标是尽可能地继承并定义增加/变化。
以下是我想出了,但我仍然不喜欢实例化一个new Class
只是为了让公共接口。我想指定最终的新公共方法。
var Child = function(name, age) {
var adult = age > 21 ? true : false;
//return new Class(name);
var api = new Class(name);
api.print = function() {
printDetails();
return this;
}
return api;
function printDetails() {
console.log('Child name', name, 'Adult', adult ? 'Yes' : 'No');
}
};
Child.prototype = Class;
Child.prototype.constructor = Child;
Child.prototype.printDetails = function() {
console.log('Child name', name, 'Adult', adult ? 'Yes' : 'No');
}
var cls = new Class('Class');
var chd = new Child('Child', 22);
cls.print();
cls.iAmA();
chd.print();
chd.iAmA();