ES5 实现 class
构造函数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18function ClassPerson (name, age) {
'use strict';
var name = arguments.length && arguments[0] !== undefined
? arguments[0]
: name
var age = arguments.length && arguments[1] !== undefined
? arguments[1]
: age
// 是否通过 new 创建
classCheck(this, ClassPerson)
this.name = name
this.age = age
}
// 检测 是否 new 实例
function classCheck (instance, constructor) {
if (!(instance instanceof constructor)) throw new Error('should exec with new keyword')
}属性方法
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
26
27
28
29
30
31
32
33var handleProps = (function () {
function defineProps (target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i]
descriptor.enumerable = descriptor.enumerable || false
descriptor.configurable = descriptor.configurable || true
Object.defineProperty(target, descriptor.key, descriptor)
}
}
return function (constructor, protoProps, staticProps) {
if (protoProps) defineProps(constructor.prototype, protoProps)
if (staticProps) defineProps(constructor, staticProps)
}
})()
// 普通方法 和 static 方法
// 可用 babel 转换 ?
handleProps(ClassPerson, [
{
key: 'getName',
value: function () {
console.log(this.name);
}
}
], [
{
key: 'getClassName',
value: function () {
console.log(this.name);
}
}
])