属性继承
function Person(name,age){this.name = name;this.age = age;}/构造函数中this指向实例对象/function Teacher(name,age,skill){// var self = this;Person.call(self,name,age)this.skill = skill;}var t = new Teacher("zhang",18,"js");console.log(t)
方法继承
function Person(name,age){this.name = name;this.age = age;}Person.prototype.sayName = function(){console.log(this.name)}function Teacher(name,age,skill){Person.call(this,name,age)this.skill = skill;}Teacher.prototype = Person.prototype;//将地址值传给了Teacher的prototype,这样就继承了Person的方法Teacher.prototype.sayAge = function(){console.log(this.age)}//未赋值之前Teacher的prototype的地址是Person的prototype地址,现在用Teacher覆盖Teacher.prototype.constructor = Teacher;var t = new Teacher("zhang",18,"js");var p = new Person("lisi",13);console.log(t)console.log(t.constructor)
class类的继承
class Person{constructor(name,age) {this.name = name;this.age = age;}sayName(){console.log(this.name)}}class Teacher extends Person {/* 类继承之后,构造函数第一行必须写super关键字 去继承父类的属性*/constructor(name,age,skill){super(name,age);this.skill = skill;}/* 在子类的方法中调用父类的方法 可以通过this或super去调用 */show(){this.sayName();// super.sayName();}}var t = new Teacher("zhang",18,"js");console.log(t)
静态属性,静态方法
属于类所独有的
特点:通过类名去调用
class Person{constructor(name,age){this.name = name;this.age = age;}static sayName(){console.log("name")}}var p = new Person("lisi",19);Person.sayName()
静态方法:
1.静态方法是属于类所独有的,类创建的时候,就会在内存中存在。不用实例化,直接通过类名直接调用,不会造成系统资源的格外浪费
2.不可以在静态方法中,调用普通方法
3.静态方法中的this,指调用静态方法的这个类
4.静态方法是可以被继承的
在静态方法中this指—>调用静态方法的类
class Person{constructor(name,age){this.name = name;this.age = age;}sayAge(){Person.sayName();console.log(this.age);}static sayName(){// this.sayAge();添加此句则报错console.log("name")}}var p = new Person("name",18)Person.sayName();p.sayAge();
1.子类可以继承父类的静态方法
2.在子类的静态方法中调用父类的静态方法,可以通过super/this去调用
class Person{static baseUrl = "https://www.baidu.com"static sayName(){console.log("name")}}class Teacher extends Person{static sayAge(){super.sayName();console.log(super.baseUrl)console.log("age");}}Teacher.sayAge()console.log(Teacher.baseUrl)
