1

I'm not able to properly override an inherited object and wondering if I can get a hand here. Been stuck for 3 days already.

say

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

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

    return {
        getValue: getValue,
        serviceArea: serviceArea
    }
}

then

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

when I run bobStu.serviceArea(); I get 'New Location', however when I run bobStu.getValue(); I get 'Old Location'

I'm passing this bobStu.getValue(); down a method that needs to call the overridden method but I can't get it to do that. Can you explain why getValue() is calling the old serviceArea()? and how to do it properly?

I've been readying this article many times and feel like it is telling me something but I'm too burnt that I can't get it :( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript#Namespace

2
  • Your Person is a factory function, not a classical constructor, and it's scoping does not care about properties. Commented Sep 27, 2016 at 23:00
  • You might find the answer in this thread stackoverflow.com/questions/12183011/… useful. Commented Sep 27, 2016 at 23:08

1 Answer 1

3

Using just serviceArea() refers only to the function serviceArea defined in the scope of Person:

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

Use this.serviceArea() instead if you want to use the serviceArea methods implemented by subclasses.

Also, constructors shouldn't return values; attach the values directly to the this value instead.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.