js中类的实现方式

构造函数方法

类的定义

1
2
3
4
5
6
7
8
9
var Animal = function(name) {
this.name = name;
}
Animal.prototype.say = function() {
console.log('say');
}

var a = new Animal('xiao');
a.say(); // "say"

类的继承

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
function extend(Child, Parent) {
var F = function(){};
F.prototype = Parent.prototype;
Child.prototype = new F();
Child.prototype.constructor = Child;
Child.uber = Parent.prototype;
}

var Cat = function(name, age) {
this.name = name;
this.age = age;
}

extend(Cat, Animal);

Cat.prototype.eat = function() {
console.log('eat');
}



var gaffey = new Cat('gaffey', 5);

gaffey.say() // "say"
gaffey.eat() // "eat"

对象方法(非构造函数)

这个方法主要是使用了es5的Object.create()函数

Object.create()函数的作用类似下面,但是真实的Object.create()要复杂的多,具体可以参看MDN关于Object.create()Polyfill

其实和上面构造函数的原理是一样的,但是上面的方式需要用到prototypethis等知识,相对复杂,所以es5出现了Object.create();

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

类的定义

1
2
3
4
5
6
7
8
var Animal = {
name: "",
say: function() {
console.log("say")
}
}

var a = Object.create(Animal)

类的继承

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var Cat = {
eat: function() {
console.log(eat);
}
}
function extend(Child, Parent) {
Object.setPrototypeOf(Child, Parent);
}

extend(Cat, Animal);

var gaffey = Object.create(Cat)

gaffey.say() // "say"
gaffey.eat() // "eat"

ES6的class

类的定义

1
2
3
4
5
6
7
8
9
10
11
class Animal {
constructor(name) {
this.name = name;
}

say() {
console.log("say");
}
}

var a = Animal('xiao');

类的继承

1
2
3
4
5
6
7
8
9
10
11
12
class Cat extends Animal {
constructor(name, age) {
super(name); // 调用父类的constructor(name)
this.age = age;
}

eat() {
console.log('eat');
}
}
var gaffey = new Cat('gaffey', 5);
console.log(gaffey);