XOR operation and inheritance of js

js XOR operation

In JavaScript, the XOR operation is represented by the symbol ^. Its function is to compare two binary numbers bit by bit. If they are the same, the result of the corresponding bit is 0, and if they are different, the result of the corresponding bit is 1. For example:

console.log(5 ^ 3); // 输出2,因为5和3的二进制分别是101和011,按位异或后得到110,即2

If one of the two operands is not a binary number, it is converted to a binary number for operation. If neither operand is of numeric type, they will be converted to string type before operation. For specific rules, please refer to JavaScript data type conversion.

js inheritance introduction

In JavaScript, inheritance can be implemented in the following ways:

  1. prototypal inheritance

Inheritance is implemented based on the prototype chain, by using the prototype object of one constructor as the prototype of another constructor.

// 父类
function Animal() {
    this.eat = function () {
        console.log('Animal eat');
    }
}

// 子类
function Dog() {
}

// 继承
Dog.prototype = new Animal();

// 创建实例
var dog = new Dog();
dog.eat(); // 输出: Animal eat

  1. Constructor inheritance

Inheritance is achieved by calling one constructor inside another constructor.

// 父类
function Animal(name) {
    this.name = name;
}

// 子类
function Dog(name) {
    Animal.call(this, name);
}

// 创建实例
var dog = new Dog('Tom');
console.log(dog.name); // 输出: Tom

  1. compositional inheritance

Implement inheritance using both prototypal inheritance and constructor inheritance.

// 父类
function Animal(name) {
    this.name = name;
}

Animal.prototype.eat = function() {
    console.log('Animal eat');
}

// 子类
function Dog(name) {
    Animal.call(this, name); // 构造函数继承
}

Dog.prototype = new Animal(); // 原型继承

// 创建实例
var dog = new Dog('Tom');
dog.eat(); // 输出: Animal eat
console.log(dog.name); // 输出: Tom

  1. ES6 extends

The class and extends keywords are new in ES6, making it easier to implement inheritance.

// 父类
class Animal {
    constructor(name) {
        this.name = name;
    }

    eat() {
        console.log('Animal eat');
    }
}

// 子类
class Dog extends Animal {
    constructor(name) {
        super(name);
    }
}

// 创建实例
let dog = new Dog('Tom');
dog.eat(); // 输出: Animal eat
console.log(dog.name); // 输出: Tom

Source: Weidian Reading    https://www.weidianyuedu.com

Guess you like

Origin blog.csdn.net/hdxx2022/article/details/132663703