js中的class类

js中的class类

函数声明和类声明之间的一个重要区别是函数声明会提升,类声明不会。需要先进行声明,再去访问,否则会报错

	var father = new Father("我是爸爸")
    class Father {
        constructor(name) {
            this.name = name;
        }
        putName(){
            console.log(this.name)
        }
    }
    // Uncaught ReferenceError: Cannot access 'Father' before initialization(在初始化之前无法访问“Person”)

constructor 方法

constructor 方法是类的默认方法,通过 new 命令生成对象实例时,自动调用该方法(默认返回实例对象 this)。一个类必须有 constructor 方法,如果没有显式定义,一个空的 constructor 方法会被默认添加。一个类只能拥有一个名为 “constructor” 的特殊方法,如果类包含多个 constructor 的方法,则将抛出 一个 SyntaxError 。

	class Father {
        constructor(name) {
            this.name = name;
        }
        putName(){
            console.log(this.name)
        }
    }
    var father = new Father("我是爸爸")
    father.putName()
  1. 在类中声明方法的时候,方法前不加 function 关键字
  2. 方法之间不要用逗号分隔,否则会报错
  3. 类的内部所有定义的方法,都是不可枚举的(non-enumerable)
  4. 一个类中只能拥有一个 constructor 方法

静态方法

静态方法可以通过类名调用,不能通过实例对象调用,否则会报错

	class Father {
        static putName(name){
            console.log(name)
        }
    }
    Father.putName("我是爸爸")
    // var father = new Father()
    // father.putName("我是爸爸 实例调用会报错") // Uncaught TypeError: father.putName is not a function

实例方法

实例方法可以通过实例对象调用,但同样不能通过类名调用,会报错

	class Father {
        constructor(){
            this.putName = function(name){
                console.log(name)
            }
        }
    }
    var father = new Father()
    father.putName("我是爸爸")
    // Father.putName("我是爸爸 类名调用会报错") // Uncaught TypeError: Father.putName is not a function

class继承

Class通过 extends 关键字实现继承。

	class Father {
        constructor(name,age){
            this.name = name
            this.age = age
        }
        putInfo(){
            console.log(this.name,this.age)
        }
    }
    class Son extends Father{
        constructor(name,age){
            super(name,age)
        }
    }
    var son = new Son("我是儿子",18)
    son.putInfo()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值