JS 对象关联设计模式 比 面向对象设计更优秀

来源:互联网 发布:ca认证是什么知乎 编辑:程序博客网 时间:2024/05/22 07:40

近看了《你不知道的JavaScript》感触很深呀,特别是其中的面向委托设计的概念,简直是给我打开了新世界的大门呀,和大家分享一下吧。


要求:

有个People对象,要求有属性name和age,sayYourself方法打印这两个变量。

有个Student对象,要求有属性grade,sayGrade方法打印这两个变量。


先说说面向对象设计:强调实体与实体之间的关系

一般会用原型继承的思想。代码如下:

/** 面向对象设计模式* 原型继承* student 继承 People*/function People (age,name) {  this.age = age;  this.name = name;}// 继承方法 sayYourSelfPeople.prototype.sayYourSelf = function(){  console.log("Your name:"+this.name+ "; Your age" + this.age);}function Student(age,name,grade){  //改变people 里的值  People.call(this,age,name);  this.grade = grade;  this.sayGrade = function(){    console.log("Your grade:"+this.grade);  }}// 创建 People 和 Student 之间的关联Student.prototype = Object.create(People.prototype);var human = new People(15,"Joy");human.sayYourSelf();//var studentA = new Student(23,"Cindy","Junior");studentA.sayYourSelf();//



这样的代码看似解决了继承的问题,但是却十分的繁琐,下面就是我推荐的面向委托,及对象关联的设计模式。


强烈推荐!!!!

对象关联的设计模式只关注对象之间的关联关系

/** 对象关联设计模式   ---- 对象与对象之间的关联关系** student 继承 People*/var Person = {  sayYourSelf: function(){    console.log("Your name:"+this.name+ "; Your age" + this.age);  },  init:function(name,age){    this.name = name;    this.age = age;  }};//创建Student对象关联Peoplevar Student = Object.create(Person);//定义Student内部方法Student.sayGrade = function(){  console.log("Your grade:"+this.grade);}Student.setGrade = function(grade){  this.grade = grade;}// 创建 和 初始化 分为两个步骤var humanA = Object.create(Person);humanA.init("Tom",23);var studentB = Object.create(Student);studentB.setGrade("Junior");


对比一下两个代码,优势就比较明显了。


优势:

1.让代码看起来更简洁。

2.避免了丑陋的显式的伪多态的调用(People.call),改为相对简单的委托调用(studentB.init)。

3.代码更加容易理解。

4.对象关联可以更好的支持关注分离原则(separation of concerns),创建和初始化并不需要合并为一个步骤。



总之今天就分享到这里啦~嘻嘻~晚安~

1 0
原创粉丝点击