I have a class
function Man(){...}
Man.drinkBeer = function(){...}
I need to inherit SuperMan
from Man
. And I still want my Superman
be able to drink some beer.
How can I do that?
I have a class
function Man(){...}
Man.drinkBeer = function(){...}
I need to inherit SuperMan
from Man
. And I still want my Superman
be able to drink some beer.
How can I do that?
Object.setPrototypeOf(SuperMan, Man);
这会将__proto__
派生函数的内部属性设置为基函数。
因此,派生函数将继承基函数的所有属性。
请注意,这会影响函数本身,而不是它们prototype
的 s。
是的,这很混乱。
没有现有的浏览器支持setPrototypeOf()
;相反,您可以使用非标准(但有效)的替代方案:
SuperMan.__proto__ = Man;
这就是CoffeeScript
类继承的作用:
var __hasProp = {}.hasOwnProperty,
__extends = function (child, parent) {
for (var key in parent) {
if (__hasProp.call(parent, key)) child[key] = parent[key];
}
function ctor() {
this.constructor = child;
}
ctor.prototype = parent.prototype;
child.prototype = new ctor();
child.__super__ = parent.prototype;
return child;
};
他们像这样使用它:
var Man = (function(){
function Man() { ... }
...
return Man;
})();
....
var SuperMan = (function(_super){
__extends(SuperMan, _super);
function SuperMan() { ... }
...
return SuperMan;
})(Man);
....