自己的理解,有错误还望指出:
在学习JavaScript的时候,我们知道他是没有类(class)的写法的,所以我们需要类的时候一般是使用构造函数来模拟类的写法。在ES6中提供了class写法,在ES5中是没有的,有时候我们在写一个构造函数的时候,使用的是function来写一个构造函数,但是这种函数式编程的方式,很难直观的发现构造函数。如下:
在ES5中,我们写一个构造函数(模拟类)的时候会这么写,可以看到这个也是一个函数,但是我将名字的第一位大写,这样可以区分于普通函数。。。并且通过this.x来将属性或者方法绑定在该构造函数里面去。
ES5写类
function Cus(a,b){
this.a = a;
this.b = b;
this.add = function (){
return this.a +this.b
}
}
var c = new Cus()
console.log(c.add())
假设我们现在使用的是ES6来写一个类,尽管提供了一个class的写法,但是下面这种写法是错的,如下:
class CUS{
this.a = 12;
this.b = 13;
this.add = function (){
return this.a +this.b
}
}
为什么不能使用this,那是因为这里的类都没有实例化,也就是说我们还没有创建一个类的实例,this是要绑定到对象上面去的,这里就要讲到ES6 的构造器constructor()
ES6写类
class Person {
constructor() {
this.firstname = "Ymw";
this.lastname = "ming";
this.add = function(){
return this.firstname+' '+this.lastname
}
}
}
var person1 = new Person();
console.log(person1.firstname+' '+person1.lastname); //Ymw ming
console.log(person1.add()); //Ymw ming
这里我把add方法也放在了构造器里面,虽然可以这么做,但是建议constructor()里面只放属性,方法写在constructor()平行位置的下边,如:
class Person {
constructor() {
this.firstname = "Ymw";
this.lastname = "ming";
this.add = function(){
return this.firstname+' '+this.lastname
}
}
say() {
return "hi,"+this.firstname+' '+this.lastname
}
}
var person1 = new Person();
console.log(person1.firstname+' '+person1.lastname);//Ymw ming
console.log(person1.add()); //Ymw ming
console.log(person1.say()); //hi,Ymw ming
class传参数
千万不要在class旁边写个括号传参数,这个是错的,一般编辑器就会提示出错了,正确的写法是写在constructor()括号内,如下:
class Person {
constructor(first,last) {
this.firstname = first;
this.lastname = last;
this.add = function(){
return this.firstname+' '+this.lastname
}
}
say() {
return "hi,"+this.firstname+' '+this.lastname
}
}
var person1 = new Person('Ymw',"ming");
console.log(person1.firstname+' '+person1.lastname);//Ymw ming
console.log(person1.add()); //Ymw ming
console.log(person1.say()); //hi,Ymw ming