如何两次扩展JavaScript原型对象?

时间:2015-12-10 08:48:53

标签: javascript inheritance prototype

很难说出我想要的内容,所以我写了一个JS示例,应该有助于明确这一点。

http://jsfiddle.net/w8Lfyxtr

  // create animal class
  var animal =  function(name) {
    this.name = name;
  };

  animal.prototype.getSound = function() {
    return this.sound === undefined ?  'nothing' : this.sound;
  };


  // create animal type classes
  var dog = new animal("dog");
  dog.prototype.sound = "woof";

  var cat = new animal("cat");
  dog.prototype.sound = "meow";

  var worm = new animal("worm");


  // create specific animals
  var spot = new dog();
  var mittens = new cat();
  var squiggles = new worm();

我想创建JavaScript函数的实例并多次扩展原型,以便在我的例子中,特定的动物具有其属和一般动物王国的方法和属性。

不幸的是,它出现在第一次实例化之后,原型属性不再存在。我不想继续扩展它,以便主要原型具有所有动物的所有方法,蠕虫和狗应该能够拥有.dig(),而猫应该能够拥有.climb()没有其他类有这些方法。

相反,我不想经常将方法重新绑定到每个实例。连指手套应该具有与猫类相同的原型,并且应该具有与克洛克山猫完全相同的功能对象,而不需要进行任何额外的任务分配。

我如何用我的例子来实现这个目标?

2 个答案:

答案 0 :(得分:1)

而不是创建特定动物的实例,即:new animal('dog'); 创建狗构造函数:

var Dog = function() {
    this.sound = 'woof';
};
Dog.prototype = animal.prototype;
new Dog();

对象没有原型属性,只有函数有。

您也可以使用Object.create:

Dog.prototype = Object.create(animal.prototype);

答案 1 :(得分:0)

这可能适合您的需要:

// create animal class
  var animal =  function(name) {
    this.name = name;
  };

  animal.prototype.getSound = function() {
    return this.sound === undefined ?  'nothing' : this.sound;
  };

  var digger = function(name) {
    animal.call(this, name);
    this.dig = function() {
      ...
    };
  }

  var climber = function(name) {
     animal.call(this, name);
     this.climb = function() {
       ...
     };
  }

  var dog = function() {
  }

  var cat = function() {
  }

  var worm = function() {
  }

  digger.prototype = new animal();
  digger.prototype.constructor = digger;

  climber.prototype = new animal();
  climber.prototype.constructor = climber;

  dog.prototype = new digger("dog");
  dog.prototype.constructor = dog;
  dog.prototype.sound = "woof";

  cat.prototype = new climber("cat");
  cat.prototype.constructor = cat;
  cat.prototype.sound = "meow";

  worm.prototype = new digger("worm");
  worm.prototype.constructor = worm;

  // create specific animals
  var spot = new dog();
  var mittens = new cat();
  var squiggles = new worm();