类首先js并没有真正的类,因为new关键词会让我们觉得js仿佛有真正的类。但是仅仅是通过new 对函数进行了构造调用。产生的实例并不是完全没有联系的。他们通过[[prototype]]建立联系。
继承的本质:说的通俗的话就是让一个类拥有使用另一个类成员变量,成员方法,静态成员的权限,避免写重复代码
function Animal(age){
this.age = age;
}
Animal.prototype.say=function(){
console.log('我叫了两声')
}
//定义了一个类 成员属性是 age ,name ,成员方法是eat
function Dog(name){
Animal.call(this,19)
this.name = name
}
Dog.prototype = Object.create(Animal.prototype)
Dog.prototype.constructor = Dog
const dog =new Dog('dog')
dog.say();//'我叫了两声'
console.log(dog instanceof Animal)//true
console.log(Dog.prototype.constructor === Dog) //true
在上面例子中。 实现了 Animal类 和 Dog 类, 其中Dog类继承了Animal类的所有方法和成员变量.这就是所谓的继承。
- es6实现类, 和类的继承
class Animal {
constructor(name) {
this.name = name
}
say() {
console.log('我的名字是' + this.name)
}
eat() {
console.log('吃饭')
}
}
class Person extends Animal {
constructor(job, age) {
super('人类')
this.job = job;
this.age = age
}
work() {
console.log(this.name + this.job)
}
get ages() {
return this.age +'岁'
}
set ages(val) {
return this.age = val
}
static war(){
console.log('发动战争')
}
}
const p1 = new Person('企业家', 21);
p1.say()
p1.work()
console.log(p1.ages)
p1.age = p1.age + 1;
console.log(p1.ages)
//我的名字是人类
//人类企业家
// 21岁
// 22岁
在这个例子中。 Person 类继承了 Animal类的所有 属性方法。
super关键字用于访问父类的构造函数。 必须在使用this前使用。不然,会报错。static 给这个类声明静态成员。 get set 访问器其实也就是加工 setter getter