es5创建对象的方式 有工厂模式,构造函数模式,原型模式和 组合使用构造函数模式+原型模式
最常使用的模式是 组合使用 构造函数模式+原型模式,这样的好处是,每个实例可以保持独特的实例属性,也可以共有原型方法
function Person(name,age){
this.name=name;
this.age=age;
}
Person.prototype.sayName=function(){
return this.name+this.age;
}
var person1=new Person('zhm',25);
在es5中我们创建对象最好的方法就是 组合构造函数模式和原型模式
而es6帮我们封装了这种模式
class Person{
construnctor(name,age){
this.name=name;
this.age=age;
}
sayName(){
return this.name+this.age;
}
}
var student=new Student('zhm',18);
Class类中的constructor方法就相当于es5中的构造函数,其实类中的所有方法都定义在了prototype上,prototype对象的constructor属性也指向class类本身,被所有实例共享
不同的是,Class只能通过new操作符调用,不能像es5中的构造函数一样,当成普通函数调用。
Class的写法就是一种语法糖,这些功能es5都能实现,只不过使用class可以让对象原型更加清晰,更接近面向对象编程。
constructor()方法是类的默认方法,所有的类都有constructor方法,如果constructor方法没有被显式定义,js会自动添加一个空的