原生 JS 中的类、静态方法、继承
常见的继承方法有原型链继承、对象冒充继承
但两者各有缺点
原型链继承:可以继承构造函数里面以及原型链上面的属性和方法,实例化子类的时候没法给父类传参
对象冒充继承:没法继承原型链上面的属性和方法
类和属性和方法
function Person(name,age) {
this.name=name;
this.age=age;
this.run=function(){
console.log(this.name+'---'+this.age);
}
}
Person.setName=function(){
console.log('静态方法');
}//静态方法
var p=new Person('zhangsan','20');//实例方法
实例方法和静态方法的区别:
实例方法是通过实例化来调用的,静态是通过类名直接调用
var p=new Person('zhangsan','20');
p.run();
p.work();
Person.setName(); /*执行静态方法*/
先看原型链继承
function Person(name,age) {
this.name=name;
this.age=age;
this.run=function(){
console.log(this.name+'---'+this.age);
}
}
Person.prototype.work=function(){
console.log('work');
}
function Web(name,age){
}
Web.prototype=new Person();
var w=new Web('李四',20);
w.run();
w.work();//undefined---undefined
//work
没法实例化
再看对象冒充继承
function Person(name,age) {
this.name=name;
this.age=age;
this.run=function(){
console.log(this.name+'---'+this.age);
}
}
Person.prototype.work=function(){
console.log('work');
}
function Web(name,age){
Person.call(this,name,age);
}
var w=new Web('李四',20);
w.run();
w.work(); //李四---20
//w.work is not a function
为了避免这两种的弊端
结合
function Person(name,age) {
this.name=name;
this.age=age;
this.run=function(){
console.log(this.name+'---'+this.age);
}
}
Person.prototype.work=function(){
console.log('work');
}
function Web(name,age){
Person.call(this,name,age);
}
Web.prototype=new Person();
var w=new Web('李四',20);
w.run();
w.work();
//李四---20
//work
ES6继承
ES6里面的类的写法
class Person{
constructor(name,age){
this.name=name;
this.age=age;
}
getInfo(){
console.log(`姓名:${this.name} 年龄:${this.age}`);
}
run(){
console.log('run')
}
}
它的继承是借助了extends
class Web extends Person{ //web继承了Person
constructor(name,age,sex){
super(name,age); /*实例化子类的时候把子类的数据传给父类*/
this.sex=sex;
}
print(){
console.log(this.sex);
}
}
var w=new Web('张三','30','男');
w.getInfo();
w.print();
//姓名:张三 年龄:30
//男