国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

ES6 class的應用實例分析

2024-05-06 15:37:24
字體:
來源:轉載
供稿:網友

本文實例講述了ES6 class的應用。分享給大家供大家參考,具體如下:

class

class 本身是個語法糖,主要為了考慮在編碼上更加人性化 內部有super,static,get 等關鍵詞 使用起來非常類似于后臺語言

使用class進行類的實現應用

'use strict';// User 類class User { constructor(name,age) {  this.name = name;  this.age = age; } static getName() {  return 'User'; } static getAge() {  return this.age; } setName(name) {  this.name = name; } setAge(age) {  this.age = age; } get info() {  return 'name:' + this.name + ' | age:' + this.age; }}// Manager 類class Manager extends User{ constructor(name,age,password){  super(name,age);  this.password = this.password; } changePwd(pwd) {  return this.password = pwd; } get info() {  var info = super.info; // 使用super繼承父級 get  return info + ' === new'; }}// typeof User: function typeof Manager: functionconsole.log('typeof User: ', typeof User, ' typeof Manager: ', typeof Manager); let manager = new Manager('Li', 22, '123456');manager.setAge(23);console.log(manager.info); // name:Li | age:23 === newconsole.log(User.prototype);console.log(Manager.prototype); 

在class之前使用原型對象定義類的應用

// 構造函數function User(name,age) { this.name = name; this.age = age;}// 原型User.prototype = { getName:function(){  return 'User'; }, setName:function(name){  this.name = name; }, getAge:function(){  return this.age; }, setAge:function(age){  this.age = age; }}// 取值函數和存執函數Object.defineProperty(User.prototype,'info', { get() {  return 'name:' + this.name + ' | age:' + this.age; }});var user = new User('Joh', 26);console.log(user); // User {name: "Joh", age: 26}// 子類function Manager(name, age, password) { User.call(this, name, age); this.password = password;}Manager.__proto__ = User; // 繼承靜態方法Manager.prototype = Object.create(User.prototype); // 繼承prototype原型方法Manager.prototype.changePwd = function (pwd) { this.password = pwd;};var manager = new Manager('Li', 22, '123456');manager.setAge(23);console.log(manager.info); // name:Li | age:23console.log(User.prototype); // 不變console.log(Manager.prototype); // {changePwd:function(){}, info:"name:undefined | age:undefined", __proto__:指向Manager.prototype}

使用 class 定義的類不被提升,需按順序執行

正常:

let user = new class User { constructor(name) {  this.name = name; }}('Joh');console.log(user); // User {name: "Joh"}

錯誤:

var man = new Man(); // 此處報錯,使用class聲明的類不會被提升 Uncaught ReferenceError: Man is not definedclass Man { constructor(name){  this.name = name; }}

更多關于JavaScript相關內容可查看本站專題:《javascript面向對象入門教程》、《JavaScript查找算法技巧總結》、《JavaScript錯誤與調試技巧總結》、《JavaScript數據結構與算法技巧總結》、《JavaScript遍歷算法與技巧總結》及《JavaScript數學運算用法總結》

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 体育| 永春县| 正安县| 循化| 临沭县| 习水县| 鲁甸县| 正宁县| 灵石县| 公安县| 中山市| 镇远县| 灵川县| 平利县| 且末县| 开江县| 金川县| 化州市| 邵阳市| 南汇区| 都匀市| 梓潼县| 阳江市| 富宁县| 墨玉县| 涿鹿县| 呼和浩特市| 四川省| 蓬安县| 绥江县| 平定县| 阿图什市| 天等县| 寻乌县| 奉贤区| 齐河县| 荣昌县| 留坝县| 盖州市| 敖汉旗| 平顺县|