在JavaScript中使用构造函数继承时,您:
-
使
prototype
原型
-
设置
constructor
属性指向“派生”构造函数。
-
this
.
这样地:
var Infant = function() {
this.age = 0;
this.color = 'pink';
this.food = 'milk';
};
Infant.prototype.eat = function(){
return ;
};
var Adolescent = function() {
Infant.call(this);
this.age = 5;
this.height = 'short';
this.job = 'keep on growing';
};
Adolescent.prototype = Object.create(Infant.prototype);
Object.defineProperty(Adolescent.prototype, "constructor",
value: Adolescent,
writable: true,
configurable: true
});
Object.create
是在ES5中添加的,所以它不会出现在像IE8这样的过时JavaScript引擎上。上面使用的单参数版本可以是
easily shimmed
在ES2015,我们可以选择使用新的
class
语义学:
class Infant {
constructor() {
this.age = 0;
this.color = 'pink';
this.food = 'milk';
}
eat() {
return ;
}
}
class Adolescent extends Infant {
constructor() {
super();
this.age = 5;
this.height = 'short';
this.job = 'keep on growing';
}
}