ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

JavaScript 自學筆記23

2022-03-03 12:34:24  阅读:130  来源: 互联网

标签:自學 name 筆記 JavaScript static Animal constructor new eat


1. JavaScript new.target 元屬性

(1). ES6提供了new.target元屬性,來檢查函數或者構造函數是否被new操作符調用。

  • 檢查函數是否被new調用:

如:function Animal(name) {

if (!new.target) { throw `Please use 'new' operator with Animal.`; };

// 如果沒有使用new操作符,將會報錯

this.name = name;

};

Animal('Cat'); // Error: Please use 'new' operator with Animal.

  • 檢查構造函數是否被new調用:

如:class Animal {

constructor(name) {

this.name = name;

console.log(new.target.name);

};};

let cat = new Animal('Cat'); // 'Animal'

2. 靜態方法

(1). ES6引入static關鍵詞來定義靜態方法

如:class Animal {

constructor(name) { this.name = name; };

get name() { return this.name; };

static greeting(){ console.log(`Hello, ${this.name}`); };

};

Animal.greeting(); // 'Hello, Animal'

(2). 在類的構造器,或實例方法中調用靜態方法的兩種語法

  • className.staticMethodName()

如:Animal.greeting(); // 'Hello, Animal'

  • this.constructor.staticMethodName()

如:let cat = new Animal('bobo');

cat.constructor.greeting(); // 'Hello, Animal'

3. 靜態屬性

與共享靜態方法相同,類的所有實例都共享靜態屬性。

(1). 使用static關鍵詞定義靜態屬性

如:class Food { static eat = 2; };

console.log(Food.eat); // 2

(2). 在構造器中調用靜態屬性的兩種語法

  • className.staticPropertyName(此語法也可以在靜態方法中調用靜態屬性)。

如:class Food { static eat = 2; };

console.log(Food.eat);

  • this.constructor.staticPropertyName

如:class Food {

static eat = 0;

constructor(name, quantity){

this.name = name;

this.quantity = quantity;

this.constructor.eat++;};

static eatCount() { return Food.eat; };

};

标签:自學,name,筆記,JavaScript,static,Animal,constructor,new,eat
来源: https://blog.csdn.net/Yvonne_Jin/article/details/123247215

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有