javascript oop覆盖继承的方法

时间:2017-01-06 13:48:14

标签: javascript oop

// 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)?

1 个答案:

答案 0 :(得分:1)

您忘记执行点击了。你的代码正在运行。 =) 我只建议将你的.doClick()方法放在A.prototype中,所以它将由所有A实例共享。

response
// 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();

https://jsfiddle.net/ekw6vk43/