Class Basic Syntax

JavaScript Class Basic Syntax (JavaScript类基本语法)

Frequently it is necessary to create many objects of the same kind. As it was already noted in chapter Constructor, operator “new”, you can do it with the help of the new function. (通常需要创建许多相同类型的对象。正如在构造函数“new”一章中已经指出的那样,您可以在新函数的帮助下执行此操作。)

In modern JavaScript, there exists a more advanced “class” construct, introducing new features that are useful for object-oriented programming. (在现代JavaScript中,存在更高级的“类”结构,引入了对面向对象编程有用的新功能。)

The “class” Syntax

The “class” Syntax (“class”语法)

The syntax is as follows:

class MyClass {
 // class methods
(//class方法)
 constructor() { ...
 }
 method1() { ...
 }
 method2() { ...
 }
 method3() { ...
 }
   ...
}

Then it would be best if you used new MyClass() for creating a new object including all the listed methods. (那么最好使用new MyClass ()来创建一个包含所有列出的方法的新对象。)

The constructor() method is automatically invoked by new. Hence, the object can be initialized there. (New会自动调用constructor ()方法。因此,可以在那里初始化对象。)

For instance:

class Site {
 constructor(siteName) {
   this.siteName = siteName;
 }
 welcome() {
   console.log(this.siteName);
 }
}
// Usage:
let site = new Site("w3cdoc");
site.welcome();

At the time a new Site(“w3cdoc”) is called, a new object is generated. Besides, the constructor runs with a particular argument assigning this.siteName to it. (在调用新站点( “w3cdoc” )时,将生成一个新对象。此外,构造函数使用特定参数运行,并为其分配this.siteName。)

Then you can call object methods. For example, site.welcome(). (然后可以调用对象方法。例如, site.welcome ()。)

It is essential to know that you should not put a comma between class methods. It results in a syntax error. (请务必了解,不应在类方法之间放置逗号。这会导致语法错误。)

Describing a Class

Describing a Class (描述课程)

For a better understanding of many complex aspects, it’s necessary to learn what a class is. (为了更好地理解许多复杂方面,有必要了解班级是什么。)

So, a JavaScript class is a kind of function. (因此, JavaScript类是一种函数。)

For instance:

class Site {
 constructor(siteName) {
   this.siteName = siteName;
 }
 welcome() {
   console.log(this.siteName);
 }
}
// proof: Site is a function
console.log(typeof Site); // function

The class Site {…} construct operates as follows:

  • It generates a function, known as Site, which becomes the result of the class declaration. The function code is derived from the constructor method. (-它生成一个名为Site的函数,该函数将成为类声明的结果。函数代码派生自构造函数方法。)

  • It stocks class methods (welcome, in Site.prototype). (-它存储类方法(欢迎使用Site.prototype )。)

Following the creation of the new Site object, it is taken from the prototype. It means that the object has access to class methods. (创建新Site对象后,将从原型中提取该对象。这意味着对象可以访问类方法。)

The code looks like this:

class Site {
 constructor(siteName) {
   this.siteName = siteName;
 }
 welcome() {
   console.log(this.siteName);
 }
}
// class is a function
console.log(typeof Site); // function
// ...or, more precisely, the constructor method
console.log(Site === Site.prototype.constructor); // true
// The methods are in Site.prototype, e.g:
console.log(Site.prototype.welcome); // cosnole.log(this.siteName);
// there are exactly two methods in the prototype
console.log(Object.getOwnPropertyNames(Site.prototype)); // constructor, welcome

More Than a “syntactic sugar”

More Than a “syntactic sugar” (不仅仅是“句法糖”)

Often the class is compared to “syntactic sugar” (a syntax that is aimed at making things easy-readable not introducing anything new) as it is possible to declare the same without using the class keyword. (通常将类与“syntactic sugar” (一种旨在使事物易于阅读而不是引入任何新事物的语法)进行比较,因为可以在不使用class关键字的情况下声明相同的语法。)

Take a look at this example:

// rewriting class Site in pure functions
// 1. Create constructor function
function Site(siteName) {
 this.siteName = siteName;
}
// any function prototype has constructor property by default,
// so we don't need to create it

// 2. Add the method to prototype
Site.prototype.welcome = function () {
 console.log(this.siteName);
};
// Usage:
let site = new Site("w3cdoc");
site.welcome();

But there exist notable differences:

class Site {
 constructor() {}
}
console.log(typeof Site); // function
Site(); // Error: Class constructor Site cannot be invoked without 'new'

Class Expression

Class Expression (类表达式)

Classes are like functions: they can be defined inside another expression, assigned, passed around, returned, and more.

is a class expression example:

let Site = class {
 welcome() {
   console.log("w3cdoc");
 }
};

Class expression can have a name. But its name is visible only inside the class. (类表达式可以具有名称。但其名称仅在类内可见。)

For instance:

// "Named Class Expression"
// that's similar to Named Function Expression, but no such term in the spec
let Site = class MyClass {
 welcome() {
   console.log(MyClass); // MyClass name is visible only inside the class
 }
};

new Site().welcome(); // works, shows MyClass definition
console.log(MyClass); // error, MyClass name isn't visible outside of the class

You even have the option of making “on-demand” classes, as follows:

function createClass(message) {
 // declare a class and return it
(//声明一个类并返回它)
 return class {
   welcome() {
     console.log(message);
   };
 };
}
// Create a new class
let Site = createClass("Welcome to w3cdoc");
new Site().welcome(); // Welcome to w3cdoc

Shorthands

Shorthands (速记)

Like literal objects, classes can include shorthands, such as getter/setters, computer properties, and more. (与文字对象一样,类可以包括速记,例如getter/setter、计算机属性等。)

In this example, the getter/setter is used:

class Site {
 constructor(siteName) {
   // invokes the setter
(//调用setter)
   this.siteName = siteName;
 }
 get siteName() {
   return this._siteName;
 }
 set siteName(value) {
   if (value.length < 3) {
     console.log("Site name is too short.");
     return;
   }
   this._siteName = value;
 }
}
let site = new Site("w3cdoc");
console.log(site.siteName); // w3cdoc
site = new Site(""); // Site name is too short.

The class declaration generates getters and setters inside Site.prototype, as follows:

Object.defineProperties(Site.prototype, {
 siteName: {
   get() {
     return this._siteName
(返回this._siteName)
   },
   set(siteName) {
     // ...
(//...)
   }
 }
});

Another example includes computed property name in brackets […]:

class Site {
 ['say' + 'Welcome']() {
   console.log("Welcome to w3cdoc");
 }
}
new Site().sayWelcome();

Class Properties

Class Properties (类属性)

Let’s try to add a property to the example above:

class Site {
 siteName = "w3cdoc";
 welcome() {
   console.log(`Welcome to ${this.siteName}!`);
 }
}
new Site().welcome();
console.log(Site.prototype.welcome); // placed in Site.prototype
console.log(Site.prototype.siteName); // undefined, not placed in Site.prototype

The name of the property is not placed into Site.prototype. It is generated by new before running the constructor. It’s a property of the object. (属性的名称未放入Site.prototype。它在运行构造函数之前由new生成。它是对象的属性。)



请遵守《互联网环境法规》文明发言,欢迎讨论问题
扫码反馈

扫一扫,反馈当前页面

咨询反馈
扫码关注
返回顶部