几类的几种方法:
1.工厂模式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
function
createObject(name,age){
var
obj =
new
Object();
obj.name = name;
obj.age = age;
obj.getName =
function
(){
return
this
.name;
};
obj.getAge =
function
(){
return
this
.age;
}
return
obj;
}
var
obj2 = createObject(
"王五"
,19);
console.log(obj2.getName());
console.log(obj2.getAge());
console.log(obj2.constructor);
|
工厂模式的方法创建对象,工厂模式可以根据接受的参数来创建一个包含必要信息的对象,可以无限次数的调用这个方法,每次都返回一个包含2个属性2个方法的对象。工厂模式解决了创建类似对象的问题,但没有解决对象的识别问题,即不能确定一个对象的类别,统一为Object。
2.构造函数法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
function
Person(name,age,job){
this
.name = name;
this
.age = age;
this
.job = job;
}
Person.prototype = {
constructor:Person,
getName:
function
(){
return
this
.name;
},
getAge:
function
(){
return
this
.age;
},
getJob:
function
(){
return
this
.job;
}
}
var
p =
new
Person(
"二麻子"
,18,
"worker"
);
console.log(p.constructor);
console.log(p.getName());
console.log(p.getAge());
console.log(p.getJob());
|
构造函数的方式虽然确定了对象的归属问题,能够确定对象的类型,但构造函数中的方法需要在每个对象中都要重新创建一遍,导致一些性能问题。
3.原型模式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
function
Person(){
}
Person.prototype = {
constructor:Person,
name:
"张三"
,
age:21,
job:
"teacher"
,
getName:
function
(){
return
this
.name;
},
getJob:
function
(){
return
this
.job;
}
}
var
p =
new
Person();
console.log(p.getName());
//张三
console.log(p.getJob());
//teacher
var
p2 =
new
Person();
p2.name =
"李四"
;
console.log(p2.getName());
//李四
|
由实例代码我们可以知道,对象实例可以访问原型中的值,但不能重写原型中的值,如果对象实例中定义了和原型重名的属性,那么该属性就会屏蔽原型中的那个属性,但并不会重写。
组合模式(构造和原型组合)
function Person(name,age){
this.name = name;
this.age = age;
}
Person.prototype.sayHello = function(){
console.log(this.name);
}
function Male(name,age){
Person.call(this,name,age);//继承实例属性
}
//Male.prototype = new Person();//继承原型方法
//Male.prototype = Person.prototype;
for(var attr in Person.prototype){
Male.prototype[attr] = Person.prototype[attr];
}
Male.prototype.sayHi = function(){
console.log("Hi");
}
var male = new Male("john",20);
male.sayHello();
male.sayHi();
var person = new Person("aaa",11);
person.sayHi();
类的继承举例
function Person(name,age){
this.name = name;
this.age = age;
this.sayHello = function(){
console.log(this.name);
}
}
/*Person.prototype.sayHello = function(){
console.log(this.name);
}*/
function Male(name,age){
Person.call(this,name,age);
}
var male = new Male("tjm",23);
male.sayHello();