码迷,mamicode.com
首页 > 编程语言 > 详细

javascript 类的区别

时间:2017-06-02 17:49:14      阅读:201      评论:0      收藏:0      [点我收藏+]

标签:extend   ict   color   静态方法   code   manage   gen   ext   man   

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 类的区别

标签:extend   ict   color   静态方法   code   manage   gen   ext   man   

原文地址:http://www.cnblogs.com/shijiu520/p/6933693.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!