JavaScript 中的方法重载

Method overload in JavaScript

本文关键字:重载 方法 JavaScript      更新时间:2023-09-26

考虑示例 html 代码:

<head>
    ....
    <script src="/js/MyClass.js"></script>
    <script src="/js/extend.js"></script>
    <script>
        $(document).ready(function($) {
            var $obj=new MyClass();
            $obj.run();
        });
    </script>
</head>
<body>

我的类.js文件:

var MyClass=function()
{
    this.run=function() {
        alert("MyClass");
    }
}

扩展.js文件:

MyClass.prototype.run=function() {
    alert("Extend");
}

为什么此代码提醒"MyClass"而不是"Extend"?如何正确重写(重载(类方法?

这一切都与 JS 如何解析像 <object>.<property/function> 这样的表达式有关。我之前已经详细解释过这一点,但这里是适用于您的案例的示意图:

[    MyClass.run    ]<=========================================================' '
MyClass[run] ===> JS checks instance for property run                           | |
 /' ||                                                                          | |
 || || --> property found @instance, resolve value------------------------------| |
 || ||                                                                          | |
 || ===========> MyClass.prototype.run could not be found? check prototype      | |
 ||      ||                                                                     | |
 ||      ||--> OR property found @MyClass.prototype, return---------------------| |
 ||      ||                                                                     | |
 ||      ==========> Object.prototype.run: not found check prototype?           | |
 ||          ||                                                                 | |
 ||          ||--> property found @Object.prototype, return---------------------|-|
 ||          ||                                                                 |=|
 ||          =======> chech prototype of Object.prototype -> undefined~~~~~~~~~~|X|
 ||                                                                             ' /
 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~< TypeError can't read property run of undefined

这是JS可以检查run属性的所有位置。因为构造函数在实例上定义了run属性(this.run = function(){};(,所以查找永远不会超过第一步:">JS检查实例的属性run"。
原型链永远不会发挥作用。

你问是否以及如何重JS方法。简短的回答是:不是,不是真的。重载是一种有效的 OOP 技术,在传统的、基于类的 OO 模型中非常方便。JS不是那样玩的,它使用原型模型代替。试图强制原型系统像传统的OO语言一样工作是可能的(由于原型系统的灵活性(,但它需要太多的努力才能跟上,而且通常不值得。
您可以将其与使用普通轿车/轿车犁田进行比较。起初,你也许可以,但用不了多久你就会被卡住,不得不叫拖拉机把你拖出田野。

如果您仍然想尝试一下,方法如下:

function MyClass()
{
    this.run = function()
    {
        console.log('child method');
        var backup = this.run;//store reference to instance property
        delete this.run;//delete instance property
        this.run();//call again
        //but now, the instance property is missing, JS will use the prototype
        this.run = backup;//restore instance property
    };
}
MyClass.prototype.run = function()
{
    console.log('prototype run method');
};
var foo = new MyClass;
foo.run();
//logs:
//child method
//prototype run method

你可能会发现看一下这里很有用,这是我更详细地解释了 JS 解析表达式的方法的上一个答案。在我的答案底部,我还添加了更多关于此事的链接,可能也值得查看它们......

仅当对象本身还没有该属性时才使用原型。

在您的情况下,您将run放在对象本身上,因此这就是run将解析的内容。

在某种程度上,你的MyClass正在覆盖它自己的原型。

也许你想要

var MyClass=function(){};
MyClass.prototype.run = function() {
    alert("MyClass");
}
var overridden = new MyClass();
overridden.run = function() {
     alert("Extend");
}

这将是一个具有与其原型不同的方法的实例。

或者,您可以链接原型来模拟类层次结构。

您的 MyClass 构造函数正在覆盖原型。以下代码将依次提醒"MyClass"、"扩展"和"覆盖"。最后一个警报显示更改实例的功能不会更改原型的功能。

var MyClass=function()
{
    this.run();
    MyClass.prototype.run = function() { alert( "Extended" ) };
    this.run();
    this.run=function() {
        alert("Overriden");
    };
    this.run();
};
MyClass.prototype.run = function() { alert( "MyClass" ); };
var myinstance = new MyClass();
alert( myinstance.run === MyClass.prototype.run );