{
// 一个类的基本定义和生成实例
// 定义一个Parent类
class Gfriend{
// 构造函数
constructor(name='甜甜圈'){
this.name=name;
}
}
let lulu = new Gfriend('v');
console.log('构造函数和实例',lulu ); // v
}
{
// 类的继承
class Gfriend{
constructor(name='甜甜圈'){
this.name=name;
}
}
// 子类 继承 父类
class Child extends Gfriend{
}
console.log('继承',new Child()); // name: '甜甜圈'
}
{
// 继承传递参数
class Gfriend{
constructor(name='甜甜圈'){
this.name=name;
}
}
class Child extends Gfriend{
constructor(name='child'){
super(name);
// 继承父类的构造函数参数列表 ,注意:super要放在构造函数的第一行
this.type='child'; // this 放在super之后
}
}
console.log('继承传递参数',new Child('hello')); // name: 'child' type: 'child'
}
{
// getter,setter
class Gfriend{
constructor(name='甜甜圈'){
this.name = name;
}
get longName(){ // 不是方法,是属性
return 'mk'+this.name
}
set longName(value){ // 给这个属性赋值,会把值赋给当前的这个name
this.name = value;
}
}
let v = new Gfriend();
console.log('getter',v.longName); // 甜甜圈
v.longName='hello';
console.log('setter',v.longName); // mkhello
}
{
// 静态方法 用static修饰
class Gfriend{
constructor(name='甜甜圈'){
this.name=name;
}
// 静态方法 ,通过类去调用,而不是通过类的实例去调用
static tell(){
console.log('tell');
}
}
Gfriend.tell(); // tell
}
{
// 静态属性
class Gfriend{
constructor(name = '甜甜圈'){
this.name = name;
}
static tell(){
console.log('tell');
}
}
Gfriend.type='test';
console.log('静态属性',Gfriend.type); // test
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之家整理,本文链接:https://www.bmabk.com/index.php/post/66474.html