构造函数
长久以来,我一直觉得js中是不存在类,其实js只是没有class或者说class关键字(当然ES2015也有了),没有class不代表没有类,面向对象语言怎么可能没有类呢,先通过代码来看看js中的类:
1 2 3 4 5 6 7
| function Range(from, to) { this.from = from, this.to = to; this.getLength = function() { console.log('length:', this.to - this.from); } }
|
类的实例对象:
1 2
| var r = new Range(2 , 8); r.getLength(); // length: 6
|
通常一个函数名如果是大写,说明这个函数是一个构造函数(这只是一个约定,没有语法约束,所以也可能不是构造函数),而构造函数就是js中的类
那么怎么判断一个函数到底是不是构造函数
所以我们来看一个构造函数需要什么,换句话说一个类需要什么(或者由什么组成):
- 属性
- 方法
属性
属性很简单,在构造函数中的this.xxx
就是属性,属性是一个对象自我特征的描述,每个实例对象都有着属于自己的属性
方法
方法有两种,第一种就是第一个例子的getLength方法,其实它也是一个属性,但是由于它是function类型的属性,可以理解为是有方法行为的属性
另一种方法就是原型方法,这个方法属于构造函数的原型,先来看一下原型方法的定义
1 2 3 4 5 6 7 8 9 10 11 12 13
| function Range(from, to) { this.from = from, this.to = to; this.getLength = function() { console.log('length:', this.to - this.from); } }
Range.prototype = { getFrom: function() { console.log('from:', this.from); } }
|
使用:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| var r = new Range(2 , 8), j = new Range(10, 30);
r.getLength(); // length: 6 r.getFrom(); // from: 2
j.getLength(); // length: 20 j.getFrom(); // from: 10
// 对原型方法进行修改 Range.prototype.getFrom: function() { console.log('from ->', this.from); }
r.getFrom(); // from -> 2 j.getFrom(); // from -> 10
|