前言:
-
原型机制 是 JS 的核心概念
-
万物皆对象, 对象 皆由 构造而生
-
构造函数的机制 就是 JS 的核心机制
从代码角度来看 构造函数的书写过于繁琐, 随着大量的 Java 程序员加入 JS 的开发中, JS的原型语法 广受吐槽, 终于在 2015年6月, JS发布了 重量级的 ES6 -- JS的第6个版本, 加入了大量的现代化编程语言的特性, 其中 class 语法就是其中之一
class语法中, 把构造函数的 两个部分整合到一起
class : 称为类
下面来看代码片段
class Rect {
// 固定名称--称为构造方法
// 当 new 类名 时, 就会触发此方法
constructor(width, height) {
console.log('constructor 被触发!');
this.width = width
this.height = height
}
// 省略 prototype, function ...
// 会自动加入到原型中
area(){
return this.width * this.height
}
zc(){
return (this.width + this.height) * 2
}
}
var r1 = new Rect(10, 20)
console.log(r1);
console.log(r1.area());
console.log(r1.zc());
上方代码简单的写了一个求面积 和 周长的两个方法(个人感觉比构造简单多的多), 其中constructor是固定的写法, 通过打印来看
两个方法都保存在原型中, 谁需要谁调用即可