原生JS(ES5)中的类
//原生JS中的类
//构造函数里面的方法和属性
function Person(name,age){
this.name=name;
this.age=age;
this.run=function(){
console.log(`${this.name} is ${this.age}岁`)
}
}
//原型链上面的属性和方法可以被多个实例共享,构造函数中的方法和属性不被多个实例共享
Person.prototype.sex='男'
Person.prototype.work=function(){
console.log(`${this.name} is ${this.sex} and ${this.age}岁`)
}
var p = new Person('jack',20) //实例方法是通过实例化来调用的,实例方法:即构造函数里面和原型链上绑定的方法
p.run()
p.work()
/**
* jack is 20岁
jack is 男 and 20岁
*/
ES6 中的类
//es6里面的类
class Person{
constructor(name,age) { //类的构造函数,实例化的时候执行,new的时候执行
this._name=name;
this._age=age;
}
getName(){
console.log(this._name);
}
setName(name){
this._name=name
}
}
var p=new Person('jack','20');
p.getName();
p.setName('Tom');
p.getName();
/**
* jack
Tom
*/