通过伪经典实例化(JavaScript)掌握原型继承
Grasping prototypical Inheritance through pseudoclassical instantiation (JavaScript)
我正在尝试通过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';
};
我想继承婴儿班的食物属性和吃法,但我的尝试失败了。 我最初的想法是分配这个。青少年=婴儿食品;但这没有用。我知道我需要将婴儿设置为超级类,但我正在旋转我的轮子
在 JavaScript 中使用构造函数进行继承时,您可以:
-
使"派生"构造函数的
prototype
属性成为其原型是"基"构造函数的prototype
属性的对象。 -
在"派生"构造函数的
prototype
属性上设置constructor
属性以指向"派生"构造函数。 -
使用正确的
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';
}
}
相关文章:
- 使用“;这个“;JavaScript原型方法中的关键字
- 引用类变量中的原型方法
- 如何从对象的原型方法访问JavaScript对象属性
- 为什么要包装每一个原型“;类“;JS中具有匿名函数的对象
- Node.js中的JavaScript原型对象效率
- 重载JS'firefox中的对象原型
- “util.inherits”和在NodeJS中扩展原型之间的区别
- 附加到原型属性的Do函数没有闭包
- 使用方括号访问插件原型函数
- 为什么JSON.stringify没有序列化原型值
- 为什么要返回'这'在导致循环的JavaScript原型中
- 带有对象/原型的链式承诺(Q延期)
- 如何覆盖原型中的事件侦听器
- 如何在Mocha/Chai中测试JS原型(非模块)
- 我将如何将Base的原型分配给User
- 原型和用法 Javascript
- 别名或以其他方式合并两个具有不同名称的相同对象原型
- JavaScript对象不是从原型链继承的
- 得到"未定义不是函数“;使用显示原型图案时出错
- 通过伪经典实例化(JavaScript)掌握原型继承