一些JS的面向对象模式

1.组合使用构造函数模式和原型模式

1
2
3
4
5
6
7
8
9
10
11
12
13
function Person(name , age , job){ 	//构造函数模式定义实例的自有属性
this.name = name;
this.age = age;
this.job = job;
this.friends = ["Shelby", "Court"]
}

Person.prototype = { //原型模式定义方法和共享属性
constructor : Person,
sayName : function(){
alert(this.name);
}
}

2.动态原型模式

1
2
3
4
5
6
7
8
9
10
function Person(name , age , job){ 	
this.name = name;
this.age = age;
this.job = job;
if (typeof this.sayName != "function"){//动态添加原型方法,首次调用实例化时添加
Person.prototype.sayName = function(){
alert(this.name);
}
}
}

3.寄生构造模式

1
2
3
4
5
6
7
8
9
10
function Person(name , age , job){ 	
var o = new Object();
o.name = name;
o.age = age;
o.job = job;
o.sayName = function(){
alert(this.name);
}
return o;
}
1
2
3
4
5
6
7
8
9
10
function SpecialArray(){
var values = new Array();
values.push.apply(values,arguments);
values.toPipedString = function(){
return this.join("|");
};
return values;
}
var colors = new SpecialArray("red","blue","green");
console.log(colors.toPipedString());

4.稳妥构造函数模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function Person(name , age , job){ 	
var o = new Object();
o.sayName = function(){
alert(name);
}
o.changeName = function(newName){
name = newName;
}
return o;
}

var friend = Person("Nicholas",29,"Software Engineer");
friend.sayName(); //alert "Nicholas"
console.log(friend.name); //shows "undefined"
friend.changeNmae("lwflky");
friend.sayName(); //alert "lwflky"
console.log(friend.name); //still shows "undefined"

这种模式除了自身的方法,没有其他办法修改实例的属性值