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

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


要求:

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

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


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

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

/*
* 面向对象设计模式
* 原型继承
* student 继承 People
*/
function People (age,name) {
  this.age = age;
  this.name = name;
}
// 继承方法 sayYourSelf
People.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对象关联People
var 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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值