JavaScript基于原型的继承

时间:2021-01-01 19:27:16

 

在一个纯粹的原型模式中,我们会摒弃类,转而专注于对象,基于原型的继承相比基于类的继承的概念上更为简单

if( typeof Object.beget  !== 'function')
{
     Object.beget = function(o) {
               var F = function() {};
               F.prototype = o;
               return new F();
      }
}
var myMammal = {
      
      name : 'Herb the Mammal',
      get_name : function() {
                return this.name;
         },
        says : function() {
                 return this.saying || ' ';
           }
};
var myCat = Object.beget(myMammal);
myCat.name = 'Henrietta';
myCat.saying = 'meow';
myCat.get_name = function() {
  return this.says + '  '+ this.name + ' '+this.says;
};