javascript中没有类,可以用一些变通的方法模拟出来,整理的几种创建类的方法。

工厂方式

缺点是不能实现私有属性和私有方法

1
2
3
4
5
6
7
8
9
10
11
function Person() {
var Obj = new Object();
Obj.name = 'attr name';
Obj.eat = function() {
console.log('method eat');
}
return Obj;
}
var person = Person();
console.log(person.name);
console.log(person.eat());

构造函数法

与工厂方式相比,使用构造函数方式创建对象,无需再函数内部重建创建对象,而使用this指代,并而函数无需明确return。

1
2
3
4
5
6
7
8
9
function Person(){
this.name = 'attr jack';
this.eat = function(){
console.log('method eat');
};
}
var person = new Person();
console.log(person.name);
console.log(person.eat());

原型方式

把属性和方法的定义放到prototype上

1
2
3
4
5
6
7
8
function Person(){}
Person.prototype.name = 'attr name';
Person.prototype.eat = function(){
console.log('method eat')
}
var person = new Person();
console.log(person.name);
console.log(person.eat());

构造函数+原型混合方式

1
2
3
4
5
6
7
8
9
function Person(){
this.name = 'attr name';
}
Person.prototype.eat = function(){
console.log('method eat')
}
var person = new Person();
console.log(person.name);
console.log(person.eat());

Object.create()法

Es6的一个新的方法Object.create(),直接返回一个对象。

1
2
3
4
5
6
7
8
9
var Person = {
name: 'attr name',
eat: function(){
console.log('method eat')
}
}
var person = Object.create(Person);
console.log(person.name);
console.log(person.eat());

老式浏览器模拟Object.create()方法

1
2
3
4
5
6
7
if (!Object.create) {
Object.create = function(o) {
function F() {};
F.prototype = o;
return new F();
}
}

缺点是不能实现私有属性和私有方法,实例对象之间也不能共享数据。

极简主义法

荷兰程序员Gabor de Mooij提出了一种比Object.create()更好的新方法,他称这种方法为”极简主义法”(minimalist approach)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var Person = {
createNew: function() {
var _person = {};
_person.name = 'attr name';
_person.eat = function() {
console.log('method eat');
}
return _person;
}
}

var person = Person.createNew();
console.log(person.name);
console.log(person.eat());

这种方法实现继承、私有属性和私有方法、数据共享也方便。

参考和引用 Javascript定义类(class)的三种方法