bar*_*a28 7 javascript inheritance class
请查看以下示例:
MyBaseClass = function(a) {
this.a = a;
};
$.extend(MyBaseClass.prototype, {
init: function() {
console.log('I am initializing the base class');
}
});
MyChildClass = $.extend(MyBaseClass, {
init: function() {
MyBaseClass.prototype.init();
console.log('I am initializing the child class');
}
});
var = new MyChildClass();
var.init();
Run Code Online (Sandbox Code Playgroud)
它应该输出'我正在初始化基类'和'我正在初始化子类'.
我需要能够继承MyBaseClass类,但仍然能够在新的init()方法的开头调用他的init()方法.
我怎么做?
Den*_*ret 18
jQuery的扩展不构建继承,而是"将两个或多个对象的内容合并到第一个对象中".
使用基于原型的继承来实现继承并显式调用"超级"方法:
MyBaseClass = function(a) {
this.a = a;
};
MyBaseClass.prototype.init = function() {
console.log('I am initializing the base class');
};
MyChildClass = function(a) {
this.a = a;
}
MyChildClass.prototype = Object.create(MyBaseClass.prototype); // makes MyChildClass "inherit" of MyBaseClass
MyChildClass.prototype.init = function() {
MyBaseClass.prototype.init.call(this); // calls super init function
console.log('I am initializing the child class');
};
var child= new MyChildClass();
child.init();
Run Code Online (Sandbox Code Playgroud)
输出:
I am initializing the base class
I am initializing the child class
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13923 次 |
| 最近记录: |