Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.2k views
in Technique[技术] by (71.8m points)

oop - How to call parent class' method from a subclass in JavaScript so that parent's local variables would be accessible?

I'm using one of the approaches to class inheritance in JavaScript (as used in the code I'm modifying), but do not understand how to attach additional functionality for a method in a subclass to the functionality the respective parent class method already has; in other words, I want to override a parent's method in the child class with a method that besides its own sub-class-specific stuff does also the same the parent's method is doing. So, I'm trying to call the parent's method from the child's method, but is it even possible?

The code is here: http://jsfiddle.net/7zMnW/. Please, open the development console to see the output.

Code also here:

function MakeAsSubclass (parent, child)
{
    child.prototype = new parent;   // No constructor arguments possible at this point.
    child.prototype.baseClass = parent.prototype.constructor;
    child.prototype.constructor = child;

    child.prototype.parent = child.prototype; // For the 2nd way of calling MethodB.
}

function Parent (inVar)
{
    var parentVar = inVar;

    this.MethodA = function () {console.log("Parent's MethodA sees parent's local variable:", parentVar);};
    this.MethodB = function () {console.log("Parent's MethodB doesn't see parent's local variable:", parentVar);};
}

function Child (inVar)
{
    Child.prototype.baseClass.apply(this, arguments);

    this.MethodB = function ()
    {
        console.log("Child's method start");
        Child.prototype.MethodB.apply(this, arguments); // 1st way
        this.parent.MethodB.apply(this, arguments); // 2 2nd way
        console.log("Child's method end");
    };
}

MakeAsSubclass(Parent, Child);

var child = new Child(7);
child.MethodA();
child.MethodB();
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

No you can't see the parents local variables. You inherit the parents prototype chain, not their local state. In your case you're applying the parent function onto the child object which does not hold the state.

apply(this,...)

means that you're binding the function to the current value of this. when you call method b from the child object, its then bound to the child, and therefore is not operating within the closure that contains the parents value.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...