1.实例对象
<script type="text/javascript"> class Person { } const p1 = new Person(); console.log(p1); </script>
控制台输出
2.代码示例:
A.通过person调用实例,那么对象就是指向person实例
<script type="text/javascript"> class Person { constructor(age, name) { this.age = age this.name = name } speak() { console.log(`my age is ${this.age},my name is ${this.name}`, ); } } const p1 = new Person(19, "劳志驰"); console.log(p1); p1.speak();
B.改变this指向的方法,使用call()函数;
p1.speak.call({ a: 1, b: 2 });
3.类的继承
class Person { constructor(age, name) { this.age = age this.name = name } speak() { console.log(`my age is ${this.age},my name is ${this.name}`, ); } } const p1 = new Person(19, "劳志驰"); class Student extends Person { constructor(age, name, address) { super(age, name); this.address = address } } const student = new Student(12, 'laozhichi', "leizhou") console.log(student);
也可以复写父类的方法:就是父类和子类都有一个speak()函数
<script type="text/javascript"> class Person { constructor(age, name) { this.age = age this.name = name } speak() { console.log(`my age is ${this.age},my name is ${this.name}`); } } const p1 = new Person(19, "劳志驰"); class Student extends Person { constructor(age, name, address) { super(age, name); this.address = address } speak() { console.log(`my age is ${this.age},my name is ${this.name},my school is ${this.address}`); } } const student = new Student(12, 'laozhichi', "leizhou") console.log(student); student.speak(); </script>