DLF*_*F85 3 javascript inheritance prototype decorator prototypal-inheritance
我正在尝试通过 JavaScript 使用继承来传递测试套件。下面是我到目前为止的代码片段:
var Infant = function() {
this.age = 0;
this.color = 'pink';
this.food = 'milk';
};
Infant.prototype.eat = function(){
return this.eat;
}
var Adolescent = function() {
this.age = 5;
this.height = 'short';
this.job = 'keep on growing';
};
Run Code Online (Sandbox Code Playgroud)
我想从 Infant 类和eat 方法继承 food 属性,但我的尝试没有成功。我最初的想法是分配 this.Adolescent = Infant.food; 但这没有用。我知道我需要将 Infant 设置为 Superclass 但我正在转动我的轮子
在 JavaScript 中使用构造函数进行继承时,您:
使prototype“派生”构造函数的属性成为一个对象,其原型是prototype“基”构造函数的属性。
将 constructor “派生”构造函数的prototype属性设置为指向“派生”构造函数。
使用正确的this.
像这样:
var Infant = function() {
this.age = 0;
this.color = 'pink';
this.food = 'milk';
};
Infant.prototype.eat = function(){
return /*...something...*/; // Returning `this.eat` doesn't make any sense, that's the function we're in
};
var Adolescent = function() {
// #3 Give super a chance to initialize the instance, you can pass args if appropriate
Infant.call(this);
this.age = 5;
this.height = 'short';
this.job = 'keep on growing';
};
// Set up Adolescent's prototype, which uses Infant's prototype property as its prototype
Adolescent.prototype = Object.create(Infant.prototype); // #1
Object.defineProperty(Adolescent.prototype, "constructor", // #2
value: Adolescent,
writable: true,
configurable: true
});
// (In pre-ES5 environments that don't event have `Object.defineProperty`, you'd use
// an assignment instead: `Adolescent.prototype.constructor = Adolescent;`
Run Code Online (Sandbox Code Playgroud)
Object.create是在 ES5 中添加的,因此它不会出现在过时的 JavaScript 引擎中,例如 IE8 中的引擎。不过,上面使用的它的单参数版本可以很容易地填充。
在 ES2015 中,我们可以选择使用新的class语义来实现:
class Infant {
constructor() {
this.age = 0;
this.color = 'pink';
this.food = 'milk';
}
eat() {
return /*...something...*/;
}
}
class Adolescent extends Infant { // extends does #1 and #2
constructor() {
super(); // #3, you can pass args here if appropriate
this.age = 5;
this.height = 'short';
this.job = 'keep on growing';
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
299 次 |
| 最近记录: |