JavaScript中传统的构造函数的写法和面向对象语言差异较大,
所以ES6中引入了类这个概念,用class关键字定义类。
传统的写法:
function Person(name,sex) {
this.name=name;
this.sex=sex;
this.show=function(){
console.log(this.name);
}
}
var obj = new Person("张三","男");
obj.show(); //张三
传统的继承:
function Manager(name,sex,age){
Person.call(this,name,sex)//这里继承Person
this.age = age;//本身加的参数
}
var obj2 = new Manager("李四","男","18");*/
console.log(obj2.name);//李四
console.log(obj2.age);//18
obj2.show(); //李四
ES6中新的定义:
class Person{
constructor(name,sex){//构造函数
this.name = name;
this.sex = sex;
}
show(){ //es6函数缩写
console.log(this.name);
}
static showName(){ //定义个静态方法 不能被实例调用和被实例继承,只能通过类的调用
return "123456";
}
}
var obj3 = new Person("王二","男");
console.log(Person.showName());//123456 静态方法只能通过类名调用
obj3.show();//王二
es6中的继承:
class Manager extends Person{//使用关键字extends
constructor(name,sex,age){//构造函数 、
super(name,sex);//使用关键字super继承哪些属性
this.age = age;
}
}
var obj4 = new Manager("麻子","男","20");
obj4.show();//麻子
console.log(Manager.showName());//123456
箭头函数:
function add(a,b){//原始函数
return a+b;
}
console.log(add(1,2));//输出3
var add2 = (c,d) => c+d;//箭头函数((c,d) => c+d)
console.log(add2(3,4));//7
var add3 = (c,d) => {c+d};
console.log(add3(3,4));//undefined
var add4 = (c,d) => {return c+d};
console.log(add4(3,4));//7 注意大括号与return必须一起出现
var add4 = (c,d) => {
console.log("我是其他的内容");
return c+d;
};//多行使用大括号
console.log(add4(3,4));//7
箭头函数里的this:
先来看一段代码:
var obj = {
a:5,
func: function (){
console.log(this.a);
},
test:function(){
console.log(this);//obj对象
setTimeout(function(){
//setTimeout函数是属于window的,所以这里面的this指window对象
console.log(this);//window对象
this.func();//报错 找不到方法
}, 1000)
}
}
obj.test();
如果要在setTimeout函数的到obj对象,以前一般都是声明一个变量接收obj,然后再通过这个变量传递进去。
var obj = {
a:5,
func: function (){
console.log(this.a);
},
test:function(){
console.log(this);//obj对象
var that = this;//定义一个that变量接收this(obj对象)
setTimeout(function(){
//setTimeout函数是属于window的,所以这里面的this指window对象
console.log(that);//obj对象
console.log(this);//window对象
that.func();//5
}, 1000)
}
}
obj.test();
箭头函数里的this始终指向函数定义时的this。
解释一下就是下面代码中setTimeout中的箭头函数里的this与外面比如说func方法里的this是一样的
var obj = {
a:5,
func:function(){
console.log(this.a); //this1
},
test:function(){
console.log(this);//obj对象 this2
setTimeout(()=>{
console.log(this);//obj对象 箭头函数里的这个this指向的是外面的this(比如说this1,this2)
this.func();//5
}, 1000)
}
}
obj.test();
所以:func,test方法不能改箭头函数,如果把test方法改成箭头函数,那么test函数里的this就指向window对象。如果把func方法改成箭头函数,那么func函数里的this也会指向window对象。
之所以这样是因为当我们使用箭头函数时,函数体内的this对象,就是定义时所在的对象,而不是使用时所在的对象。并不是因为箭头函数内部有绑定this的机制,实际原因是
箭头函数根本没有自己的this,它的this是继承外面的,因此内部的this就是外层代码块的this。