在JavaScript中覆盖函数 [英] Override function in JavaScript

查看:94
本文介绍了在JavaScript中覆盖函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

使用JavaScript原型调用基本方法

我想要继承对象将覆盖javascript中的函数。

I want to inheritance object that will override function in javascript.

从我想要调用基本方法的方法。
在这种情况下,我从 Person 继承对象 reader ,现在我想覆盖函数 getName 意思是在读者中首先我要调用 Person 上的函数,然后进行一些更改。

From the method I want to call to the base method. In this case I inherit object reader from Person and now I want to override the function getName meaning that in reader first I want to call the function on Person and then to do some changes.

<script>
    /* Class Person. */
    function Person(name) {
        this.name = name;
    }
    Person.prototype.getName = function() {
        return this.name;
    }

    var reader = new Person('John Smith');
    reader.getName = function() {
        // call to base function of Person, is it possible?
        return('Hello reader');
    }
    alert(reader.getName());
</script>


推荐答案

因为你正确地覆盖了对象本身的功能而不是它的原型,你仍然可以用你的对象调用原型函数。

Since you are correctly overriding the function on the object itself and not on its prototype, you can still call the prototype function with your object.

reader.getName = function() {
    var baseName = Person.prototype.getName.call(this);
    ...
}

这篇关于在JavaScript中覆盖函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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