Home > Web Front-end > JS Tutorial > Detailed explanation of use cases of es6's class feature

Detailed explanation of use cases of es6's class feature

php中世界最好的语言
Release: 2018-05-23 14:34:02
Original
1626 people have browsed it

This time I will bring you a detailed explanation of the use cases of es6's class features. What are the precautions when using es6's class features? Here are actual cases, let's take a look.

javaScript In languages ​​​​, the traditional way to generate instance objects is through constructors , and traditional object-oriented languages ​​(such as C and Java ) are very different. ES6 provides a writing method that is closer to traditional languages ​​and introduces the concept of class as a template for objects. Classes can be defined through the class keyword.

The difference between es6 class and es5 object-oriented:

1. The writing method is different, use the keyword class

2 .When new an instance, there is a constructor method by default, and the instance object (this) is returned by default, or another object can be returned

3. All methods of the class are on the prototype attribute, but they are not enumerable. And a semicolon cannot be used at the end of each method

4. The class must be called through a new instance, and the class uses strict mode by default

5. There is no variable promotion and must be declared first. Then call

this of 6.class by default points to the static method of the current class

7.class, use the keyword static, without new, call it directly through the class

8. How to write instance attributes and static attributes. Instance attributes are written directly inside the class using the equation (=), or they can be written in the constructor method. For static attributes, just add the keyword static before the instance attribute.

9. Class inheritance uses the keyword extends. The inheritance mechanism is completely different from es5.

The inheritance principle of es5: first new the instance object this of the subclass, and then add the methods and attributes of the parent class Add to this of the subclass (parents.call(this)).

The inheritance principle of Es6: first create the instance object this of the parent class, so if you want to use the constructor function constructor() to access the properties of the parent class using this, you must first call the super() method; and then use the constructor() of the subclass ) to modify this

10. Class inheritance can inherit the native constructor, but es5 cannot

1. General writing method (es5 and es6)

//一.ES5写法:
function Animate(name){
  this.name = name;
}
Animate.prototype.getname = function(){
  console.log(this.name)
}
var p =new Animate("lity");
p.getname();
//二.ES6,面向对象的写法,calss,
class Person{
  //constructor():构造方法是默认方法,new的时候回自动调用,如果没有显式定义,会自动添加
  //1.适合做初始化数据
  //2.constructor可以指定返回的对象
  constructor(name,age){
     this.name = name;
     this.age = age;
  }
  getval(){
    console.log(`你是${this.name},${this.age}岁`);
  }
}      
var c1 = new Person("lity",20); 
c1.getval();
Copy after login

The class of ES6 can be regarded as just a syntactic sugar, and its vast majority Some functions can be achieved with ES5

Note: The essence of class is still a function, and the class itself points to the constructor.

typeof Person  //function
Person === Person.prototype.constructor // true
Copy after login

We use some properties or methods of Object to detect instance objects written in es6

//1.查看实例对象c1的proto是否指向Person的原型(Person.prototype)
 console.log(c1.proto==Person.prototype)//true
 console.log(c1.proto)//原型对象的所有方法
 //2.isPrototypeOf:检测实例对象是否是某个函数的原型
  console.log(Person.prototype.isPrototypeOf(c1));//true
//3.constructor:查看某个对象的构造函数
   console.log(c1.constructor);
 //4.hasOwnProperty:检测某个属性是否是自己的属性;不是原型对象上的属性和方法
   console.log(c1.hasOwnProperty("name"))//true;
 //5.in:通过in可以检测属性是否在自己中(this)或者是原型中存在
    console.log("getval" in c1)//原型上存在,true
    console.log("name" in c1)//constructor(自己上存在),true
 //6.自定义检测属性是否是存在
    function hasproperty(attr,obj){
       return obj.hasOwnProperty(attr)&&(attr in obj);
    }
    console.log(hasproperty("name",c1));//true;
Copy after login

2. Expression writing method

//class表达式
const Myclass = class Me{//这里的Me是没有作用的
  constructor(name,jog){
    this.name = name;
    this.jog = jog;
  }
  getval(){
    console.log(`name is ${this.name},job is a ${this.jog}`);
  }
}
 var obj1 = new Myclass("lylt","teacher");
 obj1.getval();
Copy after login

3. Private methods of class (ES6 No writing method is provided) and private properties (no writing method is provided, the proposal is identified with #)

The so-called private methods and private properties mean that they can only be used inside the class and cannot be called outside the class

4.ES6 stipulates that the Class class has no static attributes, only static methods: static

The so-called static does not need to instantiate the object, just call it directly

class Foo {
   static classMethod() {
      return 'lity';
    }
 }
 console.log(Foo.classMethod()) // 'hello'
Copy after login

5.new.target property

new is a command that generates an instance in the constructor. ES6 provides an attribute .target for new.

Returns the class (constructor) of the instance object passed by the new command, which is generally used inside the class

//ES5:原始写法对象
function objtarge(name){
  if(new.target==undefined){
    throw new Error("必须实例化对象");
  }else{
    this.name = name
  }
}
var targets = new objtarge("litys");
console.log(targets.name);//litys
//es6写法:class内部使用new.target,返回当前的calss
class caltartget{
  constructor(name){
    console.log(new.target==caltartget);//true
    if(new.target!==caltartget){
      throw new Error("实例化对象不是caltrget");
    }else{
      this.name = name;
    }
  }
}
var caltart = new caltartget("lity");
console.log(caltart.name);//lity
Copy after login

6.this points to the

If the method of the class contains this, it will point to the instance of the class by default. However, you must be very careful. Once this method is used alone, an error is likely to be reported.

The following example

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
Copy after login

Analyze the above example: this in the prinName method points to the class Logger by default, but the method will be changed separately When called, an error will be reported. this will point to the running environment, so an error will be reported because the this.print() method cannot be found.

For the above method to solve the problem pointed by this:

(1). Use bind(this)

(2). Use the arrow function of es6 () =>{ }

(3). Use Proxy proxy

//1.bind()方法
class Logger {
 constructor() {
  this.printName = this.printName.bind(this);
 }
 // ...
}
//2.箭头函数 ()=>{}
class Logger {
 constructor() {
  this.printName = (name = 'there') => {
   this.print(`Hello ${name}`);
  };
 }
 // ...
}
//3. Porxy()
.................
Copy after login

7.class’s get() and set() methods

The same as ES5, you can use it inside the “class” Use the get and set keywords to set the value storage function and the value function for a certain attribute to intercept the access behavior of the attribute.

class MyClass {
 constructor() {
  // ...
 }
 get prop() {// 使用 get 拦截了该方法的返回值
  return 'getter';
 }
 set prop(value) {//当对该方法赋值时能获取到该赋值
  console.log('setter: '+value);
 }
}
let obj = new MyClass();
obj.prop = 123;
// setter: 123
inst.prop
// 'getter'
Copy after login

8.Inheritance

Class 可以通过extends关键字实现继承,这比 ES5 的通过修改原型链实现继承,要清晰和方便很多。

//es5 的继承
//父类
function Person(name,sex){
  this.name = name;//属性
  this.sex = sex;//属性       
}
//定义一个原型方法
Person.prototype.show = function(){
  console.log("我的姓名是"+this.name+"==="+"我的性别是"+this.sex)
}
//子类
function Worker(name,sex,job){      
  //构成函数伪装:使用call()方法绑定this,伪装继承父级的属性
  Person.call(this,name,sex);
  this.job = job;
}
//继承父类的原型方法:(介绍三种方法)
//写法一:通过遍历父级的原型一个个赋给子级的原型(es5 的原型是可枚举的,es6的不可以枚举)
(var i in Person.prototype){
  Worker.prototype[i] = Person.prototype[i];
}
//写法:重新new一个父级对象赋给子级的原型
Worker.prototype = new Person();
Worker.prototype.constructor = Worker;
//写法三:创建一个原型对象赋给子级的原型;(es5 推荐)
Worker.prototype = Object.create(Person.prototype);
Worker.prototype.constructor = Worker;
var workers = new Worker("小明","男","job")
//es6 的继承
class Person{
  constructor(name,sex){
    this.name = name;//属性
     this.sex = sex;//属性
   }
}
class Worker extends Person{
   constructor(name,sex,job){
     super();
     this.job =job;
   }
}
var workers = new Worker("小明","男","job")
Copy after login

8.1:super关键字:在子类中不同情况用法不同,既可以当作函数使用,也可以当作对象使用。

    (1):super作为函数,只能在constructor中使用:代表父类,返回子类的this

   (2):super作为对象,在普通函数中,cuper指向父类的原型对象,可以访问原型对象的属性和方法,注意,父类的实例的属性和方法是访问不了的

   (3):super作为对象,在静态方法中,cuper指向的是父类,不是父类的原型对象

示例分析如下:

//父类
class Aniamte{
  constructor(){
    if(new.target == Aniamte){
      throw new Error("本类不能实例化,只能有子类继承");
    }
  }
  //静态方法
  static getval(mgs){
    console.log("父类的static",mgs)
  }
  //普通方法      
  setname(){
    console.log("该方法有子类重写")
  }      
}
//子类
class Dog extends Aniamte{
  constructor(){
    super();//调用此方法,this才用可以用,代表父类的构造函数,返回的却是子类
    //super() ==父类.prototype.constructor.call(子类/this)
    console.log(this)//Dog {}
    this.age = 20;
    }
  //静态方法,super在静态方法中作为对象使用,指向父类;
  static getval(mgs){
    super.getval(mgs)//父类的static niceday
    console.log("子类的static",mgs)//子类的static niceday
  }
  setname(name){
    //普通方法,super作为对象使用,指向父类的原型对象,父类.prototype;
    super.setname();//该方法有子类重写
    this.name = name;
    return this.name
  }
};
Dog.getval("niceday");//静态方法,直接调用
//var parAni = new Aniamte();//报错
var dogs = new Dog();//new 一个示例对象
dogs.setname("DOYS");////DOYS
Copy after login

8.2.原生构造函数的继承,ES5不支持,ES6利用extend可以继承原生构造函数

//ESMAScript的构造函数有以下几种
/* Boolean()
* Unmber()
* String()
* Array()
* Date()
* Function()
* RegExp()
* Error()
* Object()
*/
//实例一:自定义类Myarray 继承了原生的数组的构造函数,拥有原生数组的属性和方法了
class Myarray extends Array{
  constructor(){
  super();
  console.log(this.constructor.name)//Myarray
  }
}
var myarr = new Myarray();
console.log(Object.prototype.toString.call(myarr));//[object Array]
myarr.push(1,2,1);
console.log(myarr.length)//3
Copy after login

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

vue自动化表单有哪几种方式

node+bootstrap如何搭建论坛

The above is the detailed content of Detailed explanation of use cases of es6's class feature. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template