js总结 ES6中的Class,手写简易jQuery

基础class写法

  • 首先让我们来看一个基础的class写法
class Point {
    // 定义一个Point类
    constructor(x,y){
    // 构造方法
        this.x=x;
        this.y=y;
    }
    toString(){
    // 定义toString方法
        return '('+this.x+','+this.y+')'; //通过this可以直接调用constructor中的变量
    }
}

console.log(typeof Point); //function  类的数据类型是函数
 
var point1=new Point(); // 使用的时候也是直接对类使用new命令,跟构造函数的用法完全一致。
console.log(point1.toString()); // =>(undefined,undefined)
var point2=new Point(1,1);
console.log(point2.toString()); // =>(1,1)
  • 这就是一个最基础的class类的写法,他有如下的知识点:
    - Point的类型是function
    - 在类中定义的方法,可以直接通过this调用constructor中的变量
    - 在一个类中,constructor是默认方法,通过 new 命令生成对象实例时自动调用该方法,一个类必须有 constructor 方法,如果没有显示定义,一个空的 constructor 方法会被默认添加。
    - 类必须使用 new 来调用,否则就会报错

获取类名

  • 可以通过name属性来获取类名
  • class Point{} console1.log(Point.name); //"Point"

类中的静态方法

class Foo{
   
    static classMethod(){
   
        return 'hello';
    }
}
console.log(Foo.classMethod()); //hello
let foo=new Foo();
foo.classMethod(); //Uncaught TypeError: foo.classMethod is not a function
  • 在类中的方法前面添加static可以将方法声明成静态方法
  • 表示该方法不会被实例继承,而是直接通过类调用

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值