ES6文法(4)知識の要約

クラス

JavaScriptとJavaクラスの違い>>>
プロトタイプに基づくjsクラス:クラスに基づいて
Javaを接続:コピー

ES5の模倣構造:コンストラクター(カスタムタイプ)

	function hacker(name,age){
		this.name=name;
		this.age=age;
	}
	hacker.prototype.introduce=function(){
		console.log(`我叫${this.name}`)
	}
	const one = new hacker("sagasw",21);
	const two = new hacker("kok",17);

ES6でクラスを作成する方法

	class hacker{
	constructor(name,age){
		this.name=name;
		this.age=age;
	}
	introduce(){
		console.log(`我叫${this.name}`)
	}
}
	const one = new hacker("sagasw",21);
	const two = new hacker("kok",17);

jsのクラス構文に関する注意:
类语法注意事项
1,类声明不会提升
2,类声明中的代码都自动运行在严格模式下
3,调用类必须使用new
4,类中所有的方法都是不可枚举的
5,类中的方法是不能用new调用的
6,在类的方法中重写类名报错

標準的な例:

const Dog = (function(){
	"use strict";//严格模式下
	const Dog = fuction(name,age){
		if(!(this instanceof Dog)){
			throw new Error("必须用new去调用方法")
		}
		this.name=name;
		this.age=age;
	}
	Object.defineProperty(Dog.prototype,"bark",{
		value:function(){
			if(this instanceof Dog.prototype.bark){
				throe new Error("不能使用new调用")
			}
			console.log(`我叫${this.name}`)
		}
		enumerable:false
	})
	return Dog;
})()

クラス式

	const Cat = class{
		constructor(age){
			this.age=age;
		}
	}
	const xiaomiao = new Cat(1);

クラスは一流の市民です:
関数へのパラメーターとして渡すことが
でき、関数の戻り値として使用
でき、変数に割り当てることができます

静的メンバー

	const sag = class{
		static kok(age){
			this.age=age;
		}
	}
	const xx = new sag(1);

静的メンバーのため、xxは年齢を取得しません

ゲッターとセッター

getterは属性値を取得するメソッドで、setterは属性値を設定するメソッドです
>>>>>>>

	const sag = class{
		constructor(name,age){
			this.age=age;
			this.name=name;
		}
		get galarxy(){
			console.log(`你的名字:${this.name}`);
		}
	}
	const xx = new sag(1);

セッター>>>>>>

	const sag = class{
		constructor(name,age){
			this.age=age;
			this.name=name;
		}
		set galarxy(){
			console.log(`你的名字:${this.name}`);
		}
	}
	const xx = new sag(1);

元の記事を20件公開 高く評価 19件 訪問者4868

おすすめ

転載: blog.csdn.net/qq_41136216/article/details/105533412