JavaScript 自學筆記23
2022/3/3 14:46:58
本文主要是介绍JavaScript 自學筆記23,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
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; };
};
这篇关于JavaScript 自學筆記23的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-04-26敏捷开发:想要快速交付就必须舍弃产品质量?
- 2024-04-26静态代码分析的这些好处,我竟然都不知道?
- 2024-04-26你在测试金字塔的哪一层?(下)
- 2024-04-26快刀斩乱麻,DevOps让代码评审也自动起来
- 2024-04-262024年最好用的10款ER图神器!
- 2024-04-2203-为啥大模型LLM还没能完全替代你?
- 2024-04-2101-大语言模型发展
- 2024-04-17基于SpringWeb MultipartFile文件上传、下载功能
- 2024-04-14个人开发者,Spring Boot 项目如何部署
- 2024-04-14RAG应用开发实战02-相似性检索的关键 - Embedding