// The parent class
var Parent = function (jqueryElement) {
this.jqueryElement = jqueryElement;
};
Parent.prototype.attachClick = function () {
var that = this;
this.jqueryElement.click(function (e) {
e.preventDefault();
that.doClick($(this));
});
}
Parent.prototype.doClick = function ($element) {
console.info('click event from parent');
}
// First child class
var A = function(jqueryElement) {
var that = this;
Parent.call(this, jqueryElement);
// this is supposed to override the Parent's
this.doClick = function ($element) {
console.info('click event from A');
};
};
A.prototype = Object.create(Parent.prototype);
var test = new A($('.selector'));
test.attachClick();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="selector">Click me</button>
在这个阶段,我应该看到消息"click event from A"
,但是奇怪的是,我没有看到任何消息,好像该doClick
方法从未执行过。如何doClick
在子类中覆盖继承的方法()?
您忘记了执行点击。您的代码正在运行。=)我只建议将您的.doClick()方法放在A.prototype中,这样它将被所有A实例共享。
// The parent class
var Parent = function (jqueryElement) {
this.jqueryElement = jqueryElement;
};
Parent.prototype.attachClick = function () {
var that = this;
this.jqueryElement.click(function (e) {
e.preventDefault();
that.doClick($(this));
});
}
Parent.prototype.doClick = function ($element) {
console.info('click event from parent');
}
// First child class
var A = function(jqueryElement) {
var that = this;
Parent.call(this, jqueryElement);
};
A.prototype = Object.create(Parent.prototype);
// this is supposed to override the Parent's
A.prototype.doClick = function ($element) {
console.info('click event from A');
};
var test = new A($('.selector'));
test.attachClick();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="selector">Click me</button>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句