在Javascript中覆盖方法 [英] Overriding methods in Javascript

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

问题描述

我想知道重写方法与原型和没有原型之间的区别。考虑:

I would like to know what is the difference between overriding methods with prototypes and without prototypes. Consider:

示例1:

function Animal() {
    this.sleep = function () {
        alert("animal sleeping");
    };

    this.eat = function () {
        alert("animal eating");
    };
}

function Dog() {
    this.eat = function () {
        alert("Dog eating");
    };
}

Dog.prototype = new Animal;

var dog = new Dog;

dog.eat();

示例2:

function Animal() { }

function Dog() { }

Animal.prototype.sleep = function () {
    alert("animal sleeping");
};

Animal.prototype.eat = function () {
    alert("animal eating");
};

Dog.prototype = new Animal;

Dog.prototype.eat = function () {
    alert("Dog eating");
};

var dog = new Dog;

dog.eat();

我觉得这两个例子产生的效果与 Dog class重写了 Animal 类的eat方法。或者有什么不同的事情发生?

I feel both examples produce the same effect that the Dog class is overriding the eat method of the Animal class. Or is there anything different happening?

推荐答案

在第一个方法中,每个 Animal instance将获得自己的 sleep eat 方法的实现。

In the first method each of the Animal instance will get its own implementation of sleep and eat methods.

在第二个模型中,所有实例将共享 sleep eat 方法的相同实例。

While in the second model All instances will share the same instance of the sleep and eat methods.

第二种模式更好,因为我们可以分享方法。

The second model is better since we can share the methods.

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

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