ES6 Class-Inheritance-Symbol-Template String

Table of contents

kind

 inherit

How to inherit in ES5

ES6 inheritance

Symbol

use

Can produce unique values, unique values

Resolve naming conflicts

getOwnPropertySymbols()

 Cache as global registry Symbol.for()

 Eliminate magic string

 template string


kind

In the JavaScript language, constructors are used to generate instance objects; ES6 provides the concept of Class as a template for objects. Define a class through the class keyword. ES6 classes can be regarded as another way of writing constructors.

class Person{
    constructor(name,age,gender){
        // 类构造器中属性和方法是实例私有属性和私有方法
        this.name = name;
        this.age = age;
        this.gender = gender;
    }
    // 实例公共方法 类似于存放在Person类原型对象中
    sayName(){
        console.log(this.name);
    }
    test = 'hello'; //实例公共属性
    friends = [];  //实例私有属性
    // 类静态属性和静态方法
    static personAttr = '类的静态属性';
    static personMethod = function(){
        console.log('类静态方法this指向类本身');
        console.log(this,this.personAttr,this.test,this.friends);
    }
}
let p1 = new Person('可乐',12,'male');
let p2 = new Person();
console.log(p1.test,p2.test);
console.log(p1.test === p2.test);
p1.friends.push('tom');
console.log(p1.friends,p2.friends);
console.log(p1.friends === p2.friends);
Person.personMethod();

 inherit

How to inherit in ES5

Instance use properties and methods
  1. Find the property or method from the instance object itself
  2. If the instance does not have it, find it from the prototype object of the constructor
  3. If it does not exist, find it from the prototype object of the parent constructor

/**
 * es5 继承 
 * 经典继承 原型链继承
 */
// function Animal(name,age,length,weight){
// 	this.name = name;
// 	this.age = age;
// 	this.length = length;
// 	this.weight = weight;
// }
// Animal.prototype = {
// 	constructor:Animal,
// 	sayType(){
// 		console.log(this.type)
// 	}
// }
// function Dog(name,age,length,weight,type){
// 	// 继承父构造函数属性  借用构造函数继承 经典继承
// 	Animal.call(this,name,age,length,weight);
// 	this.type = type;
// }
// // 原型链继承 子类得原型对象指向父类得实例 
// Dog.prototype = new Animal();
// Dog.prototype.constructor = Dog;
// let d1 = new Dog('可乐',12,'40cm','10kg','狗');
// d1.sayType();
// console.log(d1);

More detailed ES5 inheritance and object- oriented creation object mode and inheritance mode_Learning front-end dog-headed Sudan's blog-CSDN blog

ES6 inheritance

Class can be inherited through the extends keyword, and subclasses can have no constructor, and the system will assign it by default. If a subclass provides a constructor, super must be called explicitly. The super function is similar to a borrowed constructor. Similar to Animal.call()

1. Subclass objects point to parent class objects

2. The prototype object of the subclass inherits the prototype object of the parent class

/**
 * ES6继承 使用extends关键字实现继承
 */
class Animal{
    // 构造器属性 实例私有属性
    constructor(name,age,length){
        this.name = name;
        this.age = age;
        this.length = length;
    }
    // 类体方法 实例公共方法  存放在Animal.prototype中
    sayName(){
        console.log(this.name);
    }
    test = 'hello';
    friends = [];
    // 静态属性和静态方法
    static ParentAttr = '父类属性';
    static ParentMethod = function(a){
        console.log('父类的方法');
        return a instanceof Animal;
    }
}
// 子类继承父类     不提供constructor的情况
class Dog extends Animal{

}
let d1 = new Dog('可乐',12,'50cm');
console.log(d1);
d1.sayName();
d1.friends.push('tom')
console.log(d1.test,d1.friends,d1);
console.log(Dog.ParentAttr);
console.log(Dog.ParentMethod(d1));

// 子类继承自父类
console.log(Dog.__proto__ === Animal);
// 子类原型对象继承自父类的原型对象
console.log(Dog.prototype.__proto__ === Animal.prototype);

// 子类如果提供了构造器 必须显示调用super
// class Dog2 extends Animal{
//     constructor(name,age,weight,type,color){
//         super(name,age,weight); //相当于调用父类构造器  Animal.call()
//         this.type = type;
//         this.color = color;
//     }
//     sayName(){
//         console.log(this.name,'子类实例公共方法');
//     }
// }
// let d2 = new Dog2('可乐',12,'50cm','狗','黑色');
// console.log(d2);
// d2.sayName();

Symbol

Symbol, a new primitive data type introduced in ES6, represents a unique value. The Symbol function can accept parameters, representing the description of this unique value. It belongs to the basic data type. The Symbol() function will return a value of symbol type.

Parameters: String representing the description of this symbol value

use

Can produce unique values, unique values
let sy1 = Symbol();
let sy2 = Symbol();
console.log(sy1,sy2,sy1 === sy2,sy1.toString());

let a = new Number();
let b = new String();
console.log(a,b);

Resolve naming conflicts
let sy3 = Symbol('name'); //接收的字符串 对symbol的描述
let sy4 = Symbol('age');
let obj = {
    name:'zhangsan',
    age:12,
    [sy3]:'terry',
    [sy4]:18,
    [Symbol('email')]:"[email protected]"
}
console.log(obj);
for(let key in obj){
    console.log(key);
}

 

getOwnPropertySymbols()

 Judging from the output results in the above figure: we can find that the for in loop cannot traverse the symbol value as the attribute corresponding to the attribute name. If we want to get the attributes corresponding to all symbol values, we need to use the getOwnPropertySymbols() method .

/**
 * 获取所有的symbol值对应的属性
 * getOwnPropertySymbols
 */
console.log(Object.getOwnPropertySymbols(obj));
let s = Object.getOwnPropertySymbols(obj);  //[ Symbol(name), Symbol(age), Symbol(email) ]
console.log(obj[s[2]]);

 

 Cache as global registry Symbol.for()

The difference with global registry
Symbol() is that symbols created with the Symbol.for() method will be placed in a global symbol registry. Symbol.for() does not create a new symbol every time, it first checks whether the given key is already in the registry. If so, the last stored one will be returned directly. Otherwise, it will create a new one.

/**
 * 3.作为全局注册表 缓存 Symbol.for()
 */
// 将symbol放到全局注册表中
let sy5 = Symbol.for('hello');
let sy6 = Symbol.for('hello');
console.log(sy5 === sy6);       //true

// 每次都会创建一个不同symbol值  虽然描述符一样 但是Symbol value值不一样
let sy7 = Symbol('hello');
let sy8 = Symbol('hello');
console.log(sy7 === sy8);       //false

// Symbol.keyFor()可以检测symbol值是否在全局注册表中注册过。 返回对于symbol的描述或者undefined
console.log(Symbol.keyFor(sy5));
console.log(Symbol.keyFor(sy6));
console.log(Symbol.keyFor(sy7));

Symbol.keyFor() can detect whether the symbol value has been registered in the global registry. Returns a description of the symbol or undefined 

 Eliminate magic string

A magic string refers to a specific string or value that appears multiple times in the code and forms a strong coupling with the code.

/**
 * 4.消除魔术字符串
 */
function getArea(shape,options){
    let area = 0;
    switch(shape){
        case Shape.SJX:
            area = .5 * options.height * options.width;
            break;
        case Shape.ZFX:
            area = options.height * options.width;
            break;
        case Shape.CIRCLE:
            area = Math.PI * options.r * options.r;
            break;
        default:
            area = -1;
    }
    return area;
}
const Shape = {
    SJX:Symbol('三角形'),
    ZFX:Symbol('正方形'),
    CIRCLE:Symbol('圆'),
}
let res = getArea(Shape.SJX,{height:100,width:100,r:50})
console.log(res);

Shape.SJX = Symbol('六边形');
console.log(Shape);

 template string

Template literals are backtick ( `)-delimited literals that allow multiline strings , string interpolation with embedded expressions , and a special construct called tagged templates .

Template literals are sometimes informally called template strings because they are most commonly used for string interpolation (creating strings by replacing placeholders). However, a tagged template literal may not produce a string - it can be used with custom tag functions to perform any operation on different parts of the template literal.

/**
 * 模版字符串 可以解析变量
 */
let name = 'zhangsan';
let age = 12;
// let str = 'name' + 'age';
let str = `${name}+${age}`
console.log(str);

let id = 1;
let url = `121.199.0.35:8888/findById?id=${id}`;
console.log(url);

 

Guess you like

Origin blog.csdn.net/qq_53866767/article/details/131743144