编程语言
首页 > 编程语言> > 如何从JavaScript中的子类调用父类的方法,以便可以访问父的局部变量?

如何从JavaScript中的子类调用父类的方法,以便可以访问父的局部变量?

作者:互联网

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

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

代码也在这里:

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

解决方法:

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

apply(this,...)

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

标签:superclass,javascript,oop,inheritance
来源: https://codeday.me/bug/20191002/1843955.html