2024-07-12
한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina
Classis in ES6 saccharum syntacticum est pro programmatione objecti ordinato, modo concisam praebens structuram et mores rerum definiendi.
In lingua JavaScript, more maiorum exempla generandi res est per conditores. Infra exemplum.
function Point(x, y) {
this.x = x;
this.y = y;
}
Point.prototype.toString = function () {
return '(' + this.x + ', ' + this.y + ')';
};
var p = new Point(1, 2);
Plerumque, genus ES6 sicut saccharum syntacticum haberi potest. Pleraque eius functiones per ES5 obtineri possunt. Novus modus scribendi modus tantum facit scripturam methodi obiecti prototypi clariorem et similiorem syntaxi programmatis obiecti ordinati. In codice suprascripto adhibitis ES6 generibus revocetur, hoc modo:
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
toString() {
return '(' + this.x + ', ' + this.y + ')';
}
}
Classes ES6 aliter haberi possunt scribendi constructores;
class Point {
// ...
}
typeof Point // "function"
Point === Point.prototype.constructor // true
----------------------------------------------------------------------------
class Point {
constructor() {
// ...
}
toString() {
// ...
}
toValue() {
// ...
}
}
// 等同于
Point.prototype = {
constructor() {},
toString() {},
toValue() {},
};
1. Declarativa syntaxis: Classis keyword utere ad declarandum genus.
2. Constructor: Utere constructor methodum ad initialize in genere exempli.
3. Instantia modi: Methodus communis intra genus definita, hoc uti ad proprietates instantiae accessus.
4. modi: keyword static uti definitum et ab instantia classis non dependet.
5. Instantia proprietatibus: Initialize in conditore, vel syntaxi declarationis campi uti (scaena 3 propositio currente).
6. hereditas: impletur per keywords extendit.
7. super keywordVoca constructor seu methodus parentis classis in constructor ordinis.
8. Getter et novorum: Utere posside et pone ad accessores definiendas proprietates.
9. Privatis proprietatibus ac modis: Utere # definire proprietates et methodos privatas (scaena 3 propositio).
1. Basic genus definitionis et instantiae
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
toString() {
return `Point(${this.x}, ${this.y})`;
}
}
let point = new Point(10, 20);
console.log(point.toString()); // 输出: Point(10, 20)
2. static modi ac proprietatibus
class MathUtils {
constructor() {
console.log(MyClass.myStaticProp); // 42
}
static add(a, b) {
return a + b;
}
static myStaticProp = 42;
}
console.log(MathUtils.add(1, 2)); // 输出: 3
3. hereditas et super
class Rectangle {
constructor(width, height) {
this.width = width;
this.height = height;
}
area() {
return this.width * this.height;
}
}
class Square extends Rectangle {
constructor(sideLength) {
super(sideLength, sideLength);
}
}
let square = new Square(5);
console.log(square.area()); // 输出: 25
4. urguet et novorum
class Rectangle {
constructor(width, height) {
this.width = width;
this.height = height;
}
get area() {
return this.width * this.height;
}
set width(newWidth) {
if (newWidth > 0) {
this.width = newWidth;
} else {
console.log("Width must be positive.");
}
}
}
let rect = new Rectangle(4, 5);
console.log(rect.area); // 输出: 20
rect.width = -10; // 输出: Width must be positive.
(I) Strictioris modus
Interne, classes et moduli modo stricte per defaltam sunt, ut stricte uti non oporteat ut modum currentem definias. Quamdiu in genere vel modulo codice tuo scriptus est, tantum modus strictus praesto est. Considerans omnia codicem futurum in modulis actu currere, actu ES6 totam linguam ad strictum modum upgrades.
(2) Non est promotionis
Classes levativae variabiles non habent, quae ab ES5 omnino diversae sunt.
new Foo(); // ReferenceError
class Foo {}
//不会报错
//因为 Bar 继承 Foo 的时候, Foo 已经有定义了。
//但是,如果存在 class 的提升,上面代码就会报错,
//因为 class 会被提升到代码头部,而 let 命令是不提升的,
//所以导致 Bar 继承 Foo 的时候, Foo 还没有定义。
{
let Foo = class {};
class Bar extends Foo {
}
}
(III) nomen attributum
Cum in essentia, genus ES6 involucrum pro conditore ES5 iustum est, multae notae functionis a Classe hereditantur, incluso nomine attributi.
class Point {}
Point.name // "Point"
//name 属性总是返回紧跟在 class 关键字后面的类名。
(IV) Generator modus
Si methodus asterisco praecedit (*), significat modum functionis generatoris esse.
class Foo {
constructor(...args) {
this.args = args;
}
* [Symbol.iterator]() {
for (let arg of this.args) {
yield arg;
}
}
}
for (let x of new Foo('hello', 'world')) {
console.log(x);
}
// hello
// world
//Foo 类的 Symbol.iterator 方法前有一个星号,表示该方法是一个 Generator 函数。
//Symbol.iterator 方法返回一个 Foo 类的默认遍历器, for...of 循环会自动调用这个遍历器。
(5) Ex hoc loco
Si methodus genus hoc contineat, instantia classis per defaltam demonstrat. Sed cavendum tibi est, ut haec methodus errores faciat, si solus usus sit.
class Logger {
printName(name = 'there') {
this.print(`Hello ${name}`);
}
print(text) {
console.log(text);
}
}
const logger = new Logger();
const { printName } = logger;
printName(); // TypeError: Cannot read property 'print' of undefined
Fuge utere hoc, liga hoc in structore;
class Logger {
constructor() {
this.printName = this.printName.bind(this);
}
// ...
}
Fuge hoc utere, utere functionibus sagittarum;
class Obj {
constructor() {
this.getThis = () => this;
}
}
const myObj = new Obj();
myObj.getThis() === myObj // true
Fuge utere hoc, utere proxy
function selfish (target) {
const cache = new WeakMap();
const handler = {
get (target, key) {
const value = Reflect.get(target, key);
if (typeof value !== 'function') {
return value;
}
if (!cache.has(value)) {
cache.set(value, value.bind(target));
}
return cache.get(value);
}
};
const proxy = new Proxy(target, handler);
return proxy;
}
const logger = selfish(new Logger());