Javascript函数继承与原型 [英] Javascript functional inheritance with prototypes

查看:90
本文介绍了Javascript函数继承与原型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Douglas Crockford的 JavaScript:The Good Parts 中,他建议我们使用功能继承。这是一个例子:

In Douglas Crockford's JavaScript: The Good Parts he recommends that we use functional inheritance. Here's an example:

var mammal = function(spec, my) {
    var that = {};
    my = my || {};

    // Protected
    my.clearThroat = function() { 
        return "Ahem";
    };

    that.getName = function() {
        return spec.name;
    };

    that.says = function() {
        return my.clearThroat() + ' ' + spec.saying || '';
    };

    return that;
};

var cat = function(spec, my) {
    var that = {};
    my = my || {};

    spec.saying = spec.saying || 'meow';
    that = mammal(spec, my);

    that.purr = function() { 
        return my.clearThroat() + " purr"; 
    };

    that.getName = function() { 
        return that.says() + ' ' + spec.name + ' ' + that.says();
    };

    return that;
};

var kitty = cat({name: "Fluffy"});

我遇到的主要问题是,每次我做一个哺乳动物 cat JavaScript解释器必须重新编译其中的所有函数。也就是说,您无法在实例之间共享代码。

The main issue I have with this is that every time I make a mammal or cat the JavaScript interpreter has to re-compile all the functions in it. That is, you don't get to share the code between instances.

我的问题是:如何使此代码更高效?例如,如果我制作了数千个 cat 对象,那么修改此模式以利用原型对象?

My question is: how do I make this code more efficient? For example, if I was making thousands of cat objects, what is the best way to modify this pattern to take advantage of the prototype object?

推荐答案

好吧,如果你计划制作大量的哺乳动物,你就是不能这样做 cat 。相反,它采用旧式的方式(原型)并通过属性继承。您仍然可以按照上面的方式执行构造函数,而不是 我的您使用隐式这个和一些代表基类的变量(在这个例子中, this.mammal )。

Well, you just can't do it that way if you plan on making lots of mammal or cat. Instead do it the old fashioned way (prototype) and inherit by property. You can still do the constructors the way you have above but instead of that and my you use the implicit this and some variable representing the base class (in this example, this.mammal).

cat.prototype.purr = function() { return this.mammal.clearThroat() + "purr"; }

我使用的另一个名字不是我的对于基本访问,并将其存储在 cat 构造函数中的中。在这个例子中,我使用哺乳动物但是如果你希望 static 访问全球哺乳动物,这可能不是最好的对象。另一种选择是将变量命名为 base

I'd use another name than my for base access and store it in this in the cat constructor. In this example I used mammal but this might not be the best if you want to have static access to the global mammal object. Another option is to name the variable base.

这篇关于Javascript函数继承与原型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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