Gramática ES6 (4) Resumen de conocimientos

Clase

Diferencia entre javascripts y clases java >>>
clase js basada en prototipo: connect
java basado en clase: copy

Estructura de imitación ES5: constructor (tipo personalizado)

	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);

Cómo escribir clases en 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);

Nota sobre la sintaxis de clase en js:
类语法注意事项
1,类声明不会提升
2,类声明中的代码都自动运行在严格模式下
3,调用类必须使用new
4,类中所有的方法都是不可枚举的
5,类中的方法是不能用new调用的
6,在类的方法中重写类名报错

Ejemplo estándar:

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;
})()

Expresión de clase

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

Las clases son ciudadanos de primera clase:
pueden pasarse como parámetros a funciones,
pueden usarse como valores de retorno de funciones,
pueden asignarse a variables

Miembro estático

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

Debido a los miembros estáticos, xx no tendrá edad

getter 与 setter

getter es un método para obtener el valor del atributo, y setter es un método para establecer el valor del atributo
getter >>>>>>>

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

setter >>>>>>

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

20 artículos originales publicados · Me gustaron 19 · Visitantes 4868

Supongo que te gusta

Origin blog.csdn.net/qq_41136216/article/details/105533412
Recomendado
Clasificación