js-class的基本语法和继承

tips

01. 不要加逗号,函数也不用加function, 加了都报错.

不要加逗号,函数也不用加function, 加了都报错.

02. 属性在实例对象上, 方法在原型上

属性在实例对象上, 方法在原型上

3. class 的类型是 function

class Person{} // 不写constructor,JavaScript 引擎会自动为它添加一个空的constructor()方法。
typeof Person // function 
Person === Person.prototype.constructor // true
let p = new Person()
p.constructor === Person.prototype.constructor // true

什么是构造函数?

顾名思义,就是构造一个实例对象的函数.

  1. class和构造函数有什么区别: class 必须new, class不能枚举
class Foo {
  constructor() {
    return Object.create(null); // 意义何在??
  }
}
new Foo() instanceof Foo // false
Foo.hasOwnProperty('x')
Object.getPrototypeOf() // 不建议用__proto__

static 是给自己类用, 不给实例用

public private protected 都是ts的修饰符

// 构造函数的方法
function Point(name,age){
	this.name = name
	this.age = age
}
Point.prototype.say = function() { // 
	return `我就叫:${this.name}, ${this.age}`
}  

// class是构造函数的语法糖
class Point {
    constructor(name, age) {
        this.name = name // this代表实例对象
        this.age = age
    }
    say() { // 相当于定义在Point.prototype上了
        return `我就叫:${this.name}, ${this.age}`
    }
}
let p = new Point('zml', 33).say()
console.log("🚀 ~ file: test.html ~ line 23 ~ p", p)

super

super() // 调用父类的构造函数...
class Animal {
    say(v) {
        console.log(v)

    }
}
class Dog extends Animal {
    wang() {
        this.say('aa')
        super.say('bb')
    }
}

new Dog().wang()

参考

  1. 阮一峰es6
  2. MDN
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值