基本使用:
ES6中class定义类其实就是Es5中定义构造函数的语法糖在代码最终解析的时候也是装化成es5形式,内部实现的内存引用关系是一样的,着所以采用class来定义是友好于从其他语言转到js的程序员,毕竟挺多是面向对象哈,哈哈~
使用class关键字创建类:
当我们在实例化一个类的时候,内部会取调用constructor方法,如果我们在类的内部没有定义constructor方法,其实内部有一个默认的constructor方法,并且constructor只能定义一次否则会报错。
constructor内部执行的操作如下:
- 创建一个空对象。
- 将类的显示原型的值赋值给创建出来对象的隐式原型。
- 函数内部的this指向,指向这个对象。
- 执行代码,向对象中添加属性。(注:方法不添加到这个对象中)
- 返回这个对象。(若没有添加属性到这个方法中,则会返回一个空对象)
类中定义属性和方法:
- 实例方法
- 访问器方法
- 类方法 (直接通过类名访问)
class Person {
constructor(name, age, height) {
this.name = name
this.age = age
this.height = height
}
// 实例方法(通过实例对象调用)
running() {
console.log(this.name + 'running')
}
// 静态方法
static staticMethod() {
console.log(this.name + 'staticMethod')
}
// 访问器
get getNameValue() {
return this.name
}
set setNameValue(newValue) {
this.name = newValue
}
}
const p = new Person('lhq', 18, 1.88)
// 印证上面的constructor内部指向步骤第4步,方法确实是没有添加到对象中,而是天添加到了Person.prototype中
console.log(p) // { name: 'lhq', age: 18, height: 1.88 }
// 使用该方法打印可看到实例方法
console.log(Object.getOwnPropertyDescriptors(Person.prototype))
// 实例方法使用
p.running() // lhqrunning 实例方法通过实例对象调用
// 静态方法使用
Person.staticMethod() // PersonstaticMethod 静态方法通过类名调用
// 访问器使用(访问器看起来是一个函数,但我们在使用的时候是和属性一样访问的,且访问器是不能传递参数的)
console.log(p.getNameValue) // lhq
p.setNameValue = 'zhangsan'
console.log(p.getNameValue) // zhangsan
下面我们将class定义类的方法通过babel转成ES5
地址:https://babeljs.io
class Person {
constructor(name, age, height) {
this.name = name
this.age = age
this.height = height
}
running() {
console.log(this.name + 'running')
}
}
babel转化后:
"use strict";
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
Object.defineProperty(Constructor, "prototype", { writable: false });
return Constructor;
}
var Person = /*#__PURE__*/function () {
function Person(name, age, height) {
_classCallCheck(this, Person);
this.name = name;
this.age = age;
this.height = height;
}
_createClass(Person, [{
key: "running",
value: function running() {
console.log(this.name + 'running');
}
}]);
return Person;
}();
欢迎交流指正,共同进步~