Home Web Front-end JS Tutorial Detailed explanation of examples of Class objects for getting started with ECMAScript6

Detailed explanation of examples of Class objects for getting started with ECMAScript6

Apr 28, 2017 am 10:01 AM

This article mainly introduces the detailed introduction to ECMAScript6 introduction-Class object. The editor thinks it is quite good. Now I will share it with you and give you a reference. Let’s follow the editor and take a look.

Object-oriented languages ​​have a sign, that is, they all have the concept of classes, through which any number of objects with the same properties and methods can be created.

There is no concept of class in ECMAScript5, so its objects are different from those in class-based languages.

The traditional way of generating objects in Javascript is through constructors

function Person(name, age){
  this.name = name;
  this.age = age;
  this.sayHello = function(){
    return "Hello "+ this.name;
  }
}

var person = new Person("dahan",18);
person.sayHello();
//Hello dahan
Copy after login

The above method is the same as the form of declaring methods in Javascript, so the distinction between objects and methods is not obvious. It's easy to get confused.

ES6 introduces the concept of Class (class). When we create objects through ES6 syntax, we can use the keyword class like Java syntax. Used to define classes. Of course, the functions of this syntax can also be realized through ES5. It just makes the definition of classes clearer and easier to understand.

//类的定义
class Person {
  //ES6中新型构造器
  constructor(name) {
    this.name = name;
  }
  //实例方法
  sayName() {
    console.log("我的名字叫"+ this.name);
  }
}
//类的继承
class Programmer extends Person {
  constructor(name) {
    //直接调用父类构造器进行初始化
    super(name);
  }
  program() {
    cosnole.log("这是我的地盘");
  }
}
//运行测试
var person = new Person('lingxiao');
var coder = new Programmer('coder');

person.sayName();
//我的名字叫lingxiao
coder.sayName();
//我的名字叫coder
coder.program();
//这是我的地盘
Copy after login

Let’s pay attention to the syntax that appears in the above code.

constructor

constructor is the default method of the class, just like the main method in Java, every class must have constructormethod.

When instantiating an object through new, the constructor method will be automatically called, and the value returned is the value returned by constructor. constructorBy default, the instance object of the current class is returned (this), but we can also specify another object. Of course, this will result in the instantiated object not being of the current class. Example.

class Person {
  constructor(){
    var ob = new Object();
    return Ob;
  }
  sayHello(){
    return "Hello World"
  }
}
var person = new Person();
person.sayHello();
//Uncaught TypeError: person.sayHello is not a function
Copy after login

When we instantiate an object, ES6 stipulates that I use the new keyword. If it is called directly, it will be called as a function.

class Person {
  constructor(name){
    this.name = name;
  }
};
var person = Person("dahan");
//Uncaught TypeError: Class constructor Person4 cannot be invoked without 'new'
Copy after login

this

In the first code, we saw this. This points to the instance itself in the class, but if we are in the method of the class If this is used, an error will occur when this method is called alone.

class Person{
  constructor(name){
    this.name = name;
  }
  sayHello() {
    return "Hello "+this.name
  }
}
var person = new Person("dahan");
var sayHello = person.sayHello;
sayHello();
//Uncaught TypeError: Cannot read property 'name' of undefined
Copy after login

For this we can simply bind it in the constructor this

class Person{
  constructor(name){
    this.name = name;
    this.sayHello = this.sayHello.call(this);
  }
  sayHello() {
    return "Hello "+this.name
  }
}
Copy after login

Inherit extend

We want If you want to extend some attributes on a class without modifying the original class, you use inheritance.

//类的继承
class Programmer extends Person {
  constructor(name,age) {
    this.age = age;//报错
    //直接调用父类构造器进行初始化
    super(name);
  }
  program() {
    cosnole.log("这是我的地盘");
  }
}
Copy after login

When using inheritance, you need to use the super keyword to call the parent class, super(name) just call the parent class’s constructor method.

In addition, when we use inheritance, the super keyword also helps us change the direction of this, so we must first call super method before using this. ES6 requires that the constructor of a subclass must execute the super function once, otherwise an error will be reported.

Finally

classThe appearance of the keyword also makes Javascript look more like an object-oriented language. I hope Javascript will get better and better. Easy to use.

The above is the detailed content of Detailed explanation of examples of Class objects for getting started with ECMAScript6. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use classes and methods in Python How to use classes and methods in Python Apr 21, 2023 pm 02:28 PM

Concepts and instances of classes and methods Class (Class): used to describe a collection of objects with the same properties and methods. It defines the properties and methods common to every object in the collection. Objects are instances of classes. Method: Function defined in the class. Class construction method __init__(): The class has a special method (construction method) named init(), which is automatically called when the class is instantiated. Instance variables: In the declaration of a class, attributes are represented by variables. Such variables are called instance variables. An instance variable is a variable modified with self. Instantiation: Create an instance of a class, a specific object of the class. Inheritance: that is, a derived class (derivedclass) inherits the base class (baseclass)

Replace the class name of an element using jQuery Replace the class name of an element using jQuery Feb 24, 2024 pm 11:03 PM

jQuery is a classic JavaScript library that is widely used in web development. It simplifies operations such as handling events, manipulating DOM elements, and performing animations on web pages. When using jQuery, you often encounter situations where you need to replace the class name of an element. This article will introduce some practical methods and specific code examples. 1. Use the removeClass() and addClass() methods jQuery provides the removeClass() method for deletion

What does class mean in python? What does class mean in python? May 21, 2019 pm 05:10 PM

Class is a keyword in Python, used to define a class. The method of defining a class: add a space after class and then add the class name; class name rules: capitalize the first letter. If there are multiple words, use camel case naming, such as [class Dog()].

Detailed explanation of PHP Class usage: Make your code clearer and easier to read Detailed explanation of PHP Class usage: Make your code clearer and easier to read Mar 10, 2024 pm 12:03 PM

When writing PHP code, using classes is a very common practice. By using classes, we can encapsulate related functions and data in a single unit, making the code clearer, easier to read, and easier to maintain. This article will introduce the usage of PHPClass in detail and provide specific code examples to help readers better understand how to apply classes to optimize code in actual projects. 1. Create and use classes In PHP, you can use the keyword class to define a class and define properties and methods in the class.

Vue error: Unable to use v-bind to bind class and style correctly, how to solve it? Vue error: Unable to use v-bind to bind class and style correctly, how to solve it? Aug 26, 2023 pm 10:58 PM

Vue error: Unable to use v-bind to bind class and style correctly, how to solve it? In Vue development, we often use the v-bind instruction to dynamically bind class and style, but sometimes we may encounter some problems, such as being unable to correctly use v-bind to bind class and style. In this article, I will explain the cause of this problem and provide you with a solution. First, let’s understand the v-bind directive. v-bind is used to bind V

How to determine whether an element has a class in jquery How to determine whether an element has a class in jquery Mar 21, 2023 am 10:47 AM

How jquery determines whether an element has a class: 1. Determine whether an element has a certain class through the "hasClass('classname')" method; 2. Determine whether an element has a certain class through the "is('.classname')" method.

How to solve the '[Vue warn]: v-bind:class/ :class' error How to solve the '[Vue warn]: v-bind:class/ :class' error Aug 26, 2023 am 08:17 AM

How to solve the "[Vuewarn]:v-bind:class/:class" error During the development process of using Vue, we often encounter some error prompts. One of the common errors is "[Vuewarn]:v-bind:class" /:class" error. This error message usually appears when we use v-bind:class or :class attribute, indicating that Vue cannot correctly parse the class value we set. Then, if

How SpringBoot encrypts and protects class files through custom classloader How SpringBoot encrypts and protects class files through custom classloader May 11, 2023 pm 09:07 PM

Background Recently, key business codes have been encrypted for the company framework to prevent the engineering code from being easily restored through decompilation tools such as jd-gui. The configuration and use of the related obfuscation scheme are relatively complex and there are many problems for the springboot project, so the class files are encrypted and then passed The custom classloder is decrypted and loaded. This solution is not absolutely safe. It only increases the difficulty of decompilation. It prevents gentlemen but not villains. The overall encryption protection flow chart is shown in the figure below. Maven plug-in encryption uses custom maven plug-in to compile. The class file specified is encrypted, and the encrypted class file is copied to the specified path. Here, it is saved to resource/corecla.

See all articles