【问题标题】:JS nested inheritanceJS嵌套继承
【发布时间】:2016-09-27 22:36:29
【问题描述】:

我无法正确覆盖继承的对象,我想知道我是否可以在这里得到帮助。已经卡了 3 天了。

function Person() { 
    function getValue(){
        serviceArea();
    }

    function serviceArea() {
        alert('Old Location');
    }

    return {
        getValue: getValue,
        serviceArea: serviceArea
    }
}

然后

function Student() {};
Student.prototype = new Person();
Student.prototype.serviceArea = function() { alert('New Location'); };
var bobStu = new Student();

当我运行bobStu.serviceArea(); 时,我得到'New Location',但是当我运行bobStu.getValue(); 时,我得到'Old Location'

我将这个bobStu.getValue(); 传递给一个需要调用被覆盖方法的方法,但我无法让它这样做。你能解释一下为什么getValue() 调用旧的serviceArea() 吗?以及如何正确地做到这一点?

我已经准备好这篇文章很多次了,感觉它在告诉我一些事情,但我太焦了,我无法理解:(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript#Namespace

【问题讨论】:

标签: javascript inheritance prototypal-inheritance


【解决方案1】:

仅使用serviceArea() 仅指在Person 范围内定义的函数serviceArea

function Person() { 
    function getValue(){
        serviceArea();  // this...
    }

    // ...always refers to this, independent of the object you're constructing
    function serviceArea() {
        alert('Old Location');
    }

    // also note this:
    this.getValue = getValue;
    this.serviceArea = serviceArea;
}

如果您想使用由子类实现的serviceArea 方法,请改用this.serviceArea()

另外,构造函数不应该返回值;而是将值直接附加到 this 值。

【讨论】:

    猜你喜欢
    • 2011-06-19
    • 1970-01-01
    • 2017-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-04
    • 1970-01-01
    相关资源
    最近更新 更多