Reputation: 602
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
Upvotes: 1
Views: 146
Reputation: 40894
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.
Upvotes: 3