如何从JavaScript中的子类调用父类的方法,以便可以访问父的局部变量? [英] How to call parent class' method from a subclass in JavaScript so that parent's local variables would be accessible?

查看:1114
本文介绍了如何从JavaScript中的子类调用父类的方法,以便可以访问父的局部变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JavaScript中的一种类继承方法(在我正在修改的代码中使用),但是不了解如何将子类中的方法的附加功能附加到相应父类的功能方法已经有了;换句话说,我想用一个方法覆盖子类中的父方法,该方法除了它自己的子类特定的东西外,父方法也在做同样的事情。所以,我试图从孩子的方法调用父方法,但它是否可能?

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?

代码在这里: http://jsfiddle.net/7zMnW/ 。请打开开发控制台查看输出。

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

此处代码:

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();


推荐答案

不,你看不到父母的局部变量。你继承了父母原型链,而不是他们的本地状态。在您的情况下,您将父函数应用于不保持状态的子对象。

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,...)

表示您将函数绑定到此函数的当前值。当您从子对象调用方法b时,它然后绑定到子对象,因此不在包含父值的闭包内操作。

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.

这篇关于如何从JavaScript中的子类调用父类的方法,以便可以访问父的局部变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆