2016-09-27 107 views
1

我无法正确覆盖继承的对象,并想知道我是否可以在这里找到一只手。已经被卡住了3天了。JS嵌套继承

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

+0

你的'Person'是一个工厂函数,不是一个经典的构造函数,它的范围并不关心属性。 – Bergi

+0

你可能会在这个线程中找到答案http://stackoverflow.com/questions/12183011/javascript-redefine-and-override-existing-function-body有用。 – Rosa

回答

3

只需使用serviceArea()仅指功能serviceAreaPerson范围定义:

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; 
} 

使用this.serviceArea(),而是如果你想使用由子类实现的serviceArea方法

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