JS 对象关联设计模式 比 面向对象设计更优秀
2015-11-19 23:24
696 查看
最近看了《你不知道的JavaScript》感触很深呀,特别是其中的面向委托设计的概念,简直是给我打开了新世界的大门呀,和大家分享一下吧。
要求:
有个People对象,要求有属性name和age,sayYourself方法打印这两个变量。
有个Student对象,[b]要求有属性grade,sayGrade方法打印这两个变量。[/b]
先说说面向对象设计:强调实体与实体之间的关系
一般会用原型继承的思想。代码如下:
这样的代码看似解决了继承的问题,但是却十分的繁琐,下面就是我推荐的面向委托,及对象关联的设计模式。
[b]强烈推荐!!!![/b]
[b]对象关联的设计模式:只关注对象之间的关联关系
[/b]
对比一下两个代码,优势就比较明显了。
优势:
1.让代码看起来更简洁。
2.避免了丑陋的显式的伪多态的调用(People.call),改为相对简单的委托调用(studentB.init)。
3.代码更加容易理解。
4.对象关联可以更好的支持关注分离原则(separation of concerns),创建和初始化并不需要合并为一个步骤。
总之今天就分享到这里啦~嘻嘻~晚安~
要求:
有个People对象,要求有属性name和age,sayYourself方法打印这两个变量。
有个Student对象,[b]要求有属性grade,sayGrade方法打印这两个变量。[/b]
先说说面向对象设计:强调实体与实体之间的关系
一般会用原型继承的思想。代码如下:
/* * 面向对象设计模式 * 原型继承 * 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();//
这样的代码看似解决了继承的问题,但是却十分的繁琐,下面就是我推荐的面向委托,及对象关联的设计模式。
[b]强烈推荐!!!![/b]
[b]对象关联的设计模式:只关注对象之间的关联关系
[/b]
/* * 对象关联设计模式 ---- 对象与对象之间的关联关系 * * 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),创建和初始化并不需要合并为一个步骤。
总之今天就分享到这里啦~嘻嘻~晚安~
相关文章推荐
- headroom.js 用例,漂亮完善的 鼠标滚动 --->导航栏隐藏显示效果
- 第23篇 js快速学习知识
- PrimeFaces 核心源码 js
- 珠联璧合:组合 R 语言和 D3.js 的力量
- JSP基础
- JS 简单回调函数实现
- jsp修改example5-6
- JSON数据转换
- [Web前端]梳理-JavaScript.2.变量与量. 3.数据类型
- JavaScript初学笔记
- 原生js实现tab选项卡里内嵌图片滚动特效代码
- javascript两种禁止一个函数没有运行结束时就再次调用的方法
- jq实现最多复选框,js数组操作实践。
- jq实现最多复选框,js数组操作实践。
- 外部引入js文件不生效解决方法
- 自适应浏览器分辨率的javascript函数[转]
- JavaScript中的null和undefined
- extjs5中使用echart让图表更丰富
- 手写js面向对象选项卡插件
- JS中变量名作为if条件的真/假