您的位置:首页 > Web前端 > JavaScript

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

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

要求:

有个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),创建和初始化并不需要合并为一个步骤。





总之今天就分享到这里啦~嘻嘻~晚安~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: