如人可以继承以外,js也存在继承。
ES5中的继承;
function People(name,age,sex){
this.name = name;
this.age = age;
this.sex = sex;
}//原始的类型。
function Man(name,age,sex,iden){
this.iden = iden;
People.call(this,name,age,sex)
//通过call让Man能用People的东西
}
var zs = new Man('zs',18,'man','xs')
通过上例还可以让一个构造函数继承多个构造函数。
es5中原型链的继承;
function People(name,age,sex){
this.name = name;
this.age = age;
this.sex =sex;
People.prototype.run=function()
{console.log('跑步中...')}//原型链上加上方发,实例化的对象能用
}
var zs = new People
zs.run();
ES6中继承原型链上的方法:
class People{
constructor(name,age,sex){
this.name=name;
this.age = age;
this.sex =sex;
}//constructor就是对于Es5中的People构造函数
run(){
console.log('跑步中...')
}
}
es5中自定义的原型链:
function Fn1(name){
this.name =name;
Fn1.prototype.run=function(){
console.log('跑步中...')
}
}
function Fn2(age){
this.age =age;
Fn2.prototype.cahng=function(){
console.log('唱歌中...')
}
}
function Fn3(sex){
this.sex =sex;
Fn3.prototype.tiao=function(){
console.log('跳舞中...')
}
}
//改变前 fn1 ---> fn1.prototype ------>Object.prototype
Fn1.prototype.__proto__ = new Fn2
Fn2.prototype.__proto__ = new Fn3
var fn1 = new Fn1('zs')
//fn1 的原型链就变成 fn1 ---> fn1.prototype ---> fn2.prototype ---> fn3.prototype
//------>Object.prototype
es6中的自定义原型链:
class Fn1{
constructor(name){
this.name =name;
}
run(){
console.log('跑步中..')
}
}
class Fn2 extends Fn1{
constructor(age){
super();
this.age =age;
}
tiao(){
console.log('跳舞中..')
}
}
class Fn3 extends Fn2{ //extends ----继承 Fn3 继承 Fn2
constructor(sex){
super();
this.sex =sex;
}
zhang(){
console.log('唱歌中..')
}
}
new fn3();
//fn3 的原型链就变成 fn3 ---> fn3.prototype ---> fn2.prototype ---> fn1.prototype
//------>Object.prototype
class 的静态方法和属性:
在 class 里面 的原型链上的方法或者属性前面加上 一个关键字 static 关键字即可 -----表示自己才能用。
注意 : class 和 let 类似:
class 不 能 重 复 声 明; class 不 能 变量 提升。