[javaScript essay] 04 class in ES6

class in es6

In fact, the two keywords var and function in js, plus closures, are enough.

The class keyword is pushed by es6. As a js chicken, frankly speaking, it's tasteless to eat, but it's a pity to abandon.

1.class writing

Constructor is constructor, toString method can be copied

class Person {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    };
    addAge() {
        this.age++;
        alert(this.age);
    };
    toString() {
        return '[name='+this.name+',age='+this.age+']';
    };
}

let person = new Person('Zhang San', '23');
person.addAge();
console.log(person.toString());

2. Static method and example method

class $ {
    constructor(dom) {
        this.dom = document.querySelector(dom);
    };
    static ajax() {
        alert('Send out ajax');
    };
    html(str) {
        this.dom.innerHTML = str;
    };
};
$.ajax();
new $('#app').html('<p>Hello</p>');

3. Inherit simple play

class Animal {
    constructor(age, name) {
        this.age = age;
        this.name = name;
    };
    eat() {
        alert(this.name + 'Eat at');
    };
}
class Dog extends Animal {
    constructor(age, name, color) {
        super(age, name);
        this.color = color;
    };
    run() {
        alert(this.color +' The dog is running.');
    };
}
let dog = new Dog('24', 'Siberian Husky', 'Red');
dog.eat();
dog.run();

4. Private attributes and private methods

No ~ ~ ~

5. thinking

Look at the following code:

// es6
class A {

};
// es5
class A ({

});

As can be seen from the above figure, the two are surprisingly similar.

Sanhe small steel gun has a conjecture: es6 does not redefine class, but encapsulates the function of es5.

es6 needs to specify the constructor because the map is behind class. To construct a class, a constructor must be called. Static methods can be specified directly with static. But the problem is that it's hard to control private methods and variables, so we choose to give up!.

6. Write a class function by yourself

My class will be based on the following call

var Person = myClass({
    constructor: function(name){
        this.name = name;
    },
    static:{
        saySleep: function() {
            alert('good night');
        }
    },
    sayName: function() {
        alert(this.name);
    },
    sayHello: function(){
        alert('sayHello');
    }
});
var p = new Person('Siberian Husky');
console.log(p);
p.sayHello();
p.sayName();
Person.saySleep();

The implementation logic is as follows:

function myClass(conf) {
    var constructor = conf.constructor;
    var staticFn = conf.static;
    var constructorParameter = getParameterName(constructor);
    var constructorBody = getFnBody(constructor);
    /*Get parameter name*/
    function getParameterName(fn) {
        var fnStr = fn.toString();
        var fnargs = fnStr.slice(fnStr.indexOf('(')+1, fnStr.indexOf(')'));
        return fnargs.split(',');
    }
    /*Get function body*/
    function getFnBody(fn) {
        var fnStr = fn.toString();
        var fnBody = fnStr.slice(fnStr.indexOf('{')+1, fnStr.indexOf('}'));
        return fnBody;
    }
    /*Get all public methods*/
    function getAllFn(){
        var list = [];
        for(var fn in conf) {
            if(fn!== 'constructor' && fn != 'static') {
                list.push({
                    name: fn,
                    body: conf[fn].toString()
                });
            }
        }
        return list;
    }
    /*Compile class body*/
    function compileFnbody() {
        var fnBoby = constructorBody;
        var allFn = getAllFn();
        for(var i = 0; i < allFn.length; i++) {
            var fn = allFn[i];
            fnBoby += 'this.' + fn.name + '=' + fn.body + '; \n';
        }
        return fnBoby;
    }
    /*Compile class return*/
    function compileFn() {
        var fn = new Function(constructorParameter[0], compileFnbody());
        for (var key in staticFn) {
            fn[key] = staticFn[key];
        }
        return fn;
    }
    return compileFn();
};

Added by delphi on Fri, 03 Jan 2020 22:37:35 +0200