怎么在ES6中定义一个类和对象

发布时间:2021-04-06 17:41:44 作者:Leah
来源:亿速云 阅读:137

怎么在ES6中定义一个类和对象?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

类的基本定义和生成实例:

// 类的基本定义和生成实例
class Parent{ //定义一个类
    constructor(name='xiaxaioxian'){
     this.name= name;
    }
}
// 生成一个实例
let g_parent = new Parent();
console.log(g_parent); //{name: "xiaxaioxian"}
let v_parent = new Parent('v') // 'v'就是构造函数name属性 , 覆盖构造函数的name属性值
console.log(v_parent); // {name: "v"}

继承

// 继承
class Parent{ //定义一个类
    constructor(name='xiaxaioxian'){
     this.name= name;
    }
}
class Child extends Parent{
}
console.log('继承',new Child()) // 继承 {name: "xiaxaioxian"}

继承传递参数

// 继承传递参数
class Parent{ //定义一个类
    constructor(name='xiaxaioxian'){
     this.name= name;
    }
}
class Child extends Parent{
   constructor(name = 'child'){ // 子类重写name属性值
    super(name); // 子类向父类修改 super一定放第一行
    this.type= 'preson';
   }
}
console.log('继承',new Child('hello')) // 带参数覆盖默认值 继承{name: "hello", type: "preson"}

ES6重新定义的ES5中的访问器属性

class Parent{ //定义一个类
    constructor(name='xiaxaioxian'){
     this.name= name
    }
    get longName(){ // 属性
     return 'mk' + this.name
    }
    set longName(value){
     this.name = value
    }
}
let v = new Parent();
console.log('getter',v.longName)  // getter mkxiaxaioxian
v.longName = 'hello';
console.log('setter',v.longName)  // setter mkhello

类的静态方法:

class Parent{ //定义一个类
   constructor(name='xiaxaioxian'){
    this.name= name
   }
   static tell(){ // 静态方法:通过类去调用,而不是实例
    console.log('tell')
   }
}
Parent.tell(); // tell

类的静态属性:

// 静态属性
class Parent{ //定义一个类
   constructor(name='xiaxaioxian'){
    this.name= name
   }
   static tell(){ // 静态方法:通过类去调用,而不是实例
    console.log('tell') // tell
   }
}
Parent.type = 'test'; // 定义静态属性
console.log('静态属性',Parent.type) // 静态属性 test
let v_parent = new Parent();
console.log(v_parent); // {name: "xiaxaioxian"} 没有tell方法和type属性

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。

推荐阅读:
  1. ES6中类和对象的示例
  2. 类和对象怎么在python中使用

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

es6

上一篇:使用Dreamweaver怎么制作一个网页超链接

下一篇:怎么在Django框架中创建一个mysql连接

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》