[英]javascript oop override inherited method
// 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>
At this stage, I'm supposed to see the message "click event from A"
, but the weird thing is that I don't see any message as if the doClick
method is never executed.在这个阶段,我应该看到消息
"click event from A"
,但奇怪的是我没有看到任何消息,就好像doClick
方法从未执行过一样。 How do I override an inherited method ( doClick
) in the child class?如何覆盖子类中的继承方法 (
doClick
)?
You forgot to execute a click.您忘记执行单击。 Your code is working.
您的代码正在运行。 =) I will only suggest to put your .doClick() method in A.prototype, so it will be shared by all A instances.
=) 我只会建议将您的 .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>
https://jsfiddle.net/ekw6vk43/ https://jsfiddle.net/ekw6vk43/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.