类的构造函数constructor( ),用于传递参数,返回实例对象,通过new生成对象实例时,自动调用该方法。若未定义,系统会自动创建。
类
注意:在es6中类没有变量的提升,所以只有必须先定义类,才能通过类实例化对象。在类里面共有的属性和方法一定要加this使用。
语法:class name{ }
创建一个实例并在类中写入共有方法:
<body>
<script>
class Star{
constructor(uname,uage){
this.uname = uname;
this.uage = uage;
}
//类里面函数不需要添加function
sing(song){
console.log(this.uname+song);
}
}
var ldh = new Star("刘德华",28);
console.log(ldh);
ldh.sing("冰雨");
</script>
</body>
注意: 1) 其中this指向的是创建的实例ldh 2) 只要new,就会调用构造函数
继承 extends super
<script>
class Father{
constructor(){}
money(){
console.log(100);
}
}
class Son extends Father{ }
var son = new Son();
son.money();
</script>
警惕:下面的这段错误,应该使用super:
<script>
class Father{
constructor(x,y){
this.x = x;
this.y = y;
}
sum(x,y){
console.log(this.x+this.y);
}
}
class Son{
constructor(x,y){
this.x = x;
this.y = y;
}
}
var son = new Son(1,2);
son.sum( );
</script>
使用super:super关键字用于访问和调用对象父类上的函数。可以调用父类的构造函数,也可以调用父类的普通函数。
注意:super必须在子类this之前调用,方可调用父类中的sum方法
<script>
class Father{
constructor(x,y){
this.x = x;
this.y = y;
}
sum(){
console.log(this.x+this.y);
}
}
class Son extends Father{
constructor(x,y){
super(x,y);//调用父类中的构造函数,注意:super必须在子类this之前调用,方可调用父类中的sum方法
this.x = x;
this.y = y;
}
sub(){
console.log(this.x - this.y);
}
}
var son = new Son(5,3);
son.sub();
son.sum( );
</script>
继承原则
继承的属性或者方法查找原则是就近原则。
继承中,如果实例化子类输出一个方法,先看子类中是否有这个方法,如果有就先执行子类的方法;如果没有就去查找父类的方法。
实例:
<script>
class Father{
say(){
return "我是爸爸";
}
}
class Son extends Father{
say(){
// console.log("我是儿子");//输出:我是儿子
console.log(super.say()+'的儿子');//输出:我是爸爸的儿子
}
}
var son = new Son();
son.say( );
</script>