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

首頁 > 開發 > JS > 正文

ES6 class的應用實例分析

2024-05-06 16:52:50
字體:
來源:轉載
供稿:網友

本文實例講述了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/Ajax教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 克东县| 临西县| 云阳县| 建平县| 樟树市| 鄂尔多斯市| 民乐县| 莱芜市| 汕尾市| 湄潭县| 米脂县| 永昌县| 大方县| 浦城县| 霍林郭勒市| 南阳市| 大丰市| 北宁市| 正安县| 房山区| 梁山县| 东乌珠穆沁旗| 大连市| 孟津县| 金昌市| 怀仁县| 漳浦县| 卫辉市| 枝江市| 庆云县| 克东县| 绵竹市| 南部县| 海南省| 晋宁县| 诸城市| 麻栗坡县| 和龙市| 罗田县| 墨竹工卡县| 石狮市|