es6 class进阶【一个将class转原型对象的例子】

背景

class的出现,让js开发者告别了使用原型对象模仿面向对象中的类和类继承时代。在前端开发中,使用到class的地方非常之多,所以掌握class的用法已经必不可少了。

划重点

JS 中并没有一个真正的 class 原始类型, class 仅仅只是对原型对象运用语法糖(PS:什么是语法糖?就是不用写原始方法,而是提供了一种简单的写法,底层还是原始的方法)。所以,只有理解如何使用原型对象实现类和类继承,才能真正地用好 class。【关于使用原型对象实现类和类继承详解,后续持续更新】

来看一个class的例子

先记一个知识点:class里面可以写 三种 方法,第一种是constructor内部的方法,第二种是原型链上的方法,第三种是static函数静态方法。

class Person{
  constructor(name) {
    this.name = name;
    // constructor内部的方法,在 new 一个实例的时候就会生命这个方法,一般情况下也是在内部调用的
    function hello1() {
      console.log(`hello1 ${name}, this is an inner function!`)
    }
    hello1()
  }
  hello2() {
    console.log(`hello2 ${this.name}, this is a prototype function!`);
  }
  // 静态方法,不需要new就可以调用
  static hello3() {
    // 这里的 this.name 返回的是class的名字
    console.log(`hello3 ${this.name}, this is a static function!`); 
  }
}
const p = new Person('orchid'); 
// 结果: hello1 orchid, this is an inner function!
p.hello2();   
// 结果: hello2 orchid, this is a prototype function!
Person.hello3();   
// 结果: hello3 Person, this is a static function!
复制代码
对应的原型对象实现
function Person(name) {
  this.name = name;
  // 与上面的 hello1 对应
  function hello1() {
     console.log(`hello1 ${name}, this is an inner function!`)
  }
  hello1();
}
// 与上面的 hello2 对应
Person.prototype.hello2 = function() {
  console.log(`hello2 ${this.name}, this is a prototype function!`);
}
// 与上面的 static 方法 hello3 对应
Person.hello3  = function() {
  console.log(`hello3 ${this.name}, this is a static function!`);
}
const p = new Person('orchid');
// 结果: hello1 orchid, this is an inner function!
p.hello2();    
// 结果: hello2 orchid, this is a prototype function!
Person.hello3();   
// 结果: hello3 Person, this is a static function!
复制代码

相信你通过上面的例子已经知道了为什么说class只是一种语法糖了,代码的确是简单而且容易阅读了。

上面就是一个将es6转化为原型对象的代码实现。es6其实就是将class语法转成了原型对象实现,底部还是原型对象的代码。其实class就是一个函数而已。

本文作者简书地址

转载于:https://juejin.im/post/5c1a09a9e51d453ecd46d8d9

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值