在JavaScript中,如何使用单个“”从子类中的父类继承;.原型;块
In JavaScript, how do I inherit from a parent class in child class using a single ".prototype" block?
例如:
function Person() {
//person properties
this.name = "my name";
}
Person.prototype = {
//person methods
sayHello: function() {
console.log("Hello, I am a person.");
}
sayGoodbye: function() {
console.log("Goodbye");
}
}
function Student() {
//student specific properties
this.studentId = 0;
}
Student.prototype = {
//I need Student to inherit from Person
//i.e. the equivalent of
//Student.prototype = new Person();
//Student.prototype.constructor = Person;
//student specific methods
//override sayHello
sayHello: function() {
console.log("Hello, I am a student.");
}
}
我知道我可以使用实现这一点
function Student() {
this.studentId = 0;
}
Student.prototype = new Person();
Student.prototype.constructor = Person;
Student.prototype.sayHello = function () {
console.log("Hello, I am a student.");
}
但我想继续使用第一个例子中的样式,如果可能的话,将我所有的类方法定义在一个".protype"块中。
看看StackOverflow上的以下答案:https://stackoverflow.com/a/17893663/783743
这个答案引入了原型类同构的概念。简单地说,原型对象可以用来为类建模。以下代码取自上述答案:
function CLASS(prototype) {
var constructor = prototype.constructor;
constructor.prototype = prototype;
return constructor;
}
使用上述方法,我们可以实现Person
如下:
var Person = CLASS({
constructor: function () {
this.name = "my name";
},
sayHello: function () {
console.log("Hello, I am a person.");
},
sayGoodbye: function () {
console.log("Goodbye");
}
});
然而,继承需要一些额外的工作。因此,让我们稍微修改一下CLASS
函数:
function CLASS(prototype, base) {
switch (typeof base) {
case "function": base = base.prototype;
case "object": prototype = Object.create(base, descriptorOf(prototype));
}
var constructor = prototype.constructor;
constructor.prototype = prototype;
return constructor;
}
我们还需要为CLASS
的工作定义descriptorOf
函数:
function descriptorOf(object) {
return Object.keys(object).reduce(function (descriptor, key) {
descriptor[key] = Object.getOwnPropertyDescriptor(object, key);
return descriptor;
}, {});
}
现在我们可以如下创建Student
:
var Student = CLASS({
constructor: function () {
this.studentId = 0;
},
sayHello: function () {
console.log("Hello, I am a student.");
}
}, Person);
亲自观看演示:http://jsfiddle.net/CaDu2/
如果您需要任何理解代码的帮助,请随时与我联系。
相关文章:
- 是否可以从父类访问子类的属性
- 子类访问父类's闭包变量
- 如何通过Prototype或jquery移除子类的父类基类
- JavaScript—父类和子类/对象的此问题
- 如何在单击父类的另一个子类时获取子类的值
- hover添加类-或子类:悬停以影响父类
- jQuery父类更改的子级
- 如果类中没有子元素,则赋予父类
- 创建新的子类对象时设置父类中定义的变量时出现问题
- 如何从子类访问父类属性
- Jquery - 将父类添加到子类中的链接
- Ext.window 在父类中窗口的关闭按钮上覆盖子类中的销毁
- 在 dojo 中使用它通过父类访问子方法
- 如何定位父类和子类 I javascript
- 如何在 javascript 中从子原型调用父类的构造函数方法
- ECMAScript 6子类使用父类名称打印
- 如何在Cocos2dJS中将父类Sprite强制转换为子类MySprite
- RxJS 5子类Observable-静态方法返回父类的实例
- 如何基于子元素将类添加到父元素's类使用jQuery
- 使用jQuery更改select时更改父类父类