17.使用继承,Do not Repeat Yourself

说明

在编程中有一个原则,称为:Do not Repeat Yourself(DRY)。重复代码问题的原因是因为任何更改都需要在多个地方修复代码。这通常意味着更多的程序员的工作量和更多的错误的空间。

请注意在下面的示例中,describe方法由BirdDog共享:

Bird.prototype = {
  constructor: Bird,
  describe: function() {
    console.log("我的名字是" + this.name);
  }
};

Dog.prototype = {
  constructor: Dog,
  describe: function() {
    console.log("我的名字是" + this.name);
  }
};

describe方法在两个地方重复了。可以通过创建一个名为Animalsupertype(或父类)来编辑代码以遵循DRY原则:

function Animal() { };

Animal.prototype = {
  constructor: Animal,
  describe: function() {
    console.log("我的名字是" + this.name);
  }
};

由于Animal包含describe方法,你可以把它从BirdDog中删除:

Bird.prototype = {
  constructor: Bird
};

Dog.prototype = {
  constructor: Dog
};


练习

eat方法在CatBear中重复了。通过将eat方法移动到Animalsupertype,以DRY的原则编辑代码。

  • Animal.prototype应该有eat属性。
  • Bear.prototype不应该有eat属性。
  • Cat.prototype 不应该有eat属性。
function Cat(name) {
this.name = name; 
}

Cat.prototype = {
constructor: Cat, 
eat: function() {
console.log("nom nom nom");
}
};

function Bear(name) {
this.name = name; 
}

Bear.prototype = {
constructor: Bear, 
eat: function() {
console.log("nom nom nom");
}
};

function Animal() { }

Animal.prototype = {
constructor: Animal,

};

答案

扫描二维码关注公众号,回复: 10230802 查看本文章
方法 描述
this 当前执行代码的环境对象
prototype 给对象添加属性和方法。
constructor 返回对创建此对象的数组函数的引用。
console.log() 用于在控制台输出信息(浏览器按下 F12 打开控制台)。
function Cat(name) {
this.name = name; 
}

Cat.prototype = {
constructor: Cat, 
// eat: function() {
// console.log("nom nom nom");
// }
};

function Bear(name) {
this.name = name; 
}

Bear.prototype = {
constructor: Bear, 
// eat: function() {
// console.log("nom nom nom");
// }
};

function Animal() { }

Animal.prototype = {
constructor: Animal,
eat: function() {
console.log("nom nom nom");
}
};
发布了56 篇原创文章 · 获赞 1 · 访问量 812

猜你喜欢

转载自blog.csdn.net/weixin_44790207/article/details/105124082