我正在尝试通过 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';
};
我想继承 Infant 类的 food 属性和 eat 方法,但我的尝试没有成功。我最初的想法是分配 this.Adolescent = Infant.food;但这没有用。我知道我需要将婴儿设置为超级类,但我正在旋转我的轮子
在 JavaScript 中使用构造函数进行继承时,您:
-
使prototype
“派生”构造函数的属性,其原型是的对象prototype
“基”构造函数的属性。
-
Set the 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;`
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';
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)