Javascript functional inheritance with prototypes

后端 未结 4 1711
心在旅途
心在旅途 2021-02-01 08:58

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

var mammal = function(spec, my         


        
4条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-01 09:05

    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"; }
    

    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.

提交回复
热议问题