首页 > 代码库 > javascript 类的区别

javascript 类的区别

javascript 新式类与旧式类的区别:

es6:

  

//es6
‘use strict‘
class User{
    constructor(name,age){
        this.name = name;
        this.age = age;
    }

    //静态方法
    static getClassName(){
        return ‘User‘;
    }

    changeName(name){
        this.name = name;
    }

    changeAge(age){
        this.age = age;
    }

    get info(){
        return ‘name:‘+this.name+‘ | age:‘+this.age;
    }
}


class Manager extends User{
    constructor(name,age,password){
        super(name,age);
        this.password = password;
    }

    changePassword(password){
        this.password = password;
    }
}

console.log(typeof User);
console.log(typeof Manager)

 

es5:

  

//传统类
function User(name,age){
    this.name = name;
    this.age = age;
}

//静态方法
User.getClassName = function(){
    return ‘User‘;
};

//成员方法
User.prototype.changeName = function(name){
    this.name = name;
};

User.prototype.changeAge = function(age){
    this.age = age;
};

Object.defineProperty(User.prototype,‘info‘,{
    get(){
        return ‘name:‘+this.name+‘ | age:‘+this.age;
    }
});


//子类
function Manager(name,age,password){
    User.call(this,name,age);
    this.password = password;
}



//继承静态方法
Manager.__proto__ = User;

//继承成员方法
Manager.prototype = User.prototype;


//添加新方法:
Manager.prototype.changePassword = function(pwd){
    this.password = pwd;
}

var manager = new Manager(‘leo‘,22,‘123‘);
console.log(manager);
manager.changeName(‘zheng liang‘)
console.log(manager);

 

javascript 类的区别