栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > Web开发 > JavaScript

ES6中定义类和对象的方法示例

JavaScript 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

ES6中定义类和对象的方法示例

本文实例讲述了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属性

感兴趣的朋友可以使用在线HTML/CSS/Javascript代码运行工具:http://tools.jb51.net/code/HtmlJsRun测试上述代码运行效果。

更多关于Javascript相关内容可查看本站专题:《javascript面向对象入门教程》、《Javascript错误与调试技巧总结》、《Javascript数据结构与算法技巧总结》、《Javascript遍历算法与技巧总结》及《Javascript数学运算用法总结》

希望本文所述对大家Javascript程序设计有所帮助。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/74474.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号