对象的继承方法一共有三种,当时各有优点和缺点。下面我会用一个例子来介绍三种继承方法
创建一个人类的对象,然后分别继承学生类以及教师类
1.原型继承:把学生对象以及教师对象传入人类对象的原型中
缺点:传入的参数是根据学生对象以及教师对象所传入的参数决定的,是不能更改的
function Student(name,age){
this.name=name
this.age=age
}
Student.prototype.attendClass=function(){
console.log(this.name+"正在上课")
}
function Teach(name,age){
this.name=name
this.age=age
}
Teach.prototype.teaching=function(){
console.log(this.name+"正在教课")
}
function People(name,age){
}
People.prototype=new Student("张三",15)
var people=new People("里斯",15)
console.log(people)
people.attendClass()
上面的代码是利用原型继承,继承了Student对象的属性和方法,注意:我在创建人类对象的时候传入的参数“里斯”是显示不出来的。
2.冒充继承:把学生对象以及老师对象直接传入人类对象的构造函数内,通过改变其this的指向性,指向人类对象
优点:解决了传入参数不能修改的问题
缺点:他不能继承学生对象以及老师对象原型中的方法和属性
function Student(name,age){
this.name=name
this.age=age
}
Student.prototype.attendClass=function(){
console.log(this.name+"正在上课")
}
function Teach(name,age){
this.name=name
this.age=age
}
Teach.prototype.teaching=function(){
console.log(this.name+"正在教课")
}
function People1(name,age){
Teach.call(this,name,age)
}
var people1=new People1("王五",60)
console.log(people1)
people1.teaching()
上面的代码利用冒充继承方法。最后我写了调用teaching是调用不到的,因为people1的对象中是没有teaching方法,没有从Teach中继承到。
3.组合继承:就是上面两个方法的组合,完美的解决了问题
function Student(name,age){
this.name=name
this.age=age
}
Student.prototype.attendClass=function(){
console.log(this.name+"正在上课")
}
function Teach(name,age){
this.name=name
this.age=age
}
Teach.prototype.teaching=function(){
console.log(this.name+"正在教课")
}
function People2(name,age){
Student.call(this,name,age)
}
People2.prototype=new Student()
var people2=new People2("王麻子",20)
console.log(people2)
people2.attendClass()
ES6的一些基础知识整理
1.新增的let和const与var之间的区别
第一区别:作用域不同,let和const只在所在的块级作用域有效。
第二区别:var定义变量,存在的变量默认提升功能,let和const不会
console.log(x)
var x=20
console.log(x)
第一个x返回的结果为undefined的,而不是报错。这就相当于x已经定义了,只是还没有进行赋值,所以才不会报错。
第三区别:var定义变量可以重复定义,let和const不可以重复定义
第四区别: 利用var定义变量会自动加载到window,但是let和const不会
第五区别: let和const存在暂时性死区问题,使用let定义变量在声明之前,永远不可用
var a=30
if(true){
a=40
console.log(a)
let a=50
}
上面的代码中因为在if这个块级作用域里定义了let,那么在let定义之前输出a,就会报错,在初始化之前无法访问'a'
2.箭头函数与function之间的区别
function的特点:1.this的指向性不明确,谁调用就指向谁。
2.函数声明头具有默认的提升,函数表达式则不会。下面的代码中a1会输出,但是a2则不会,会报错。
a1();
a2();
function a1(){
console.log(111111)
}
let a2=function(){
console.log(22222)
}
3.可以作为构造函数,this会根据new指向空对象。
4.存在arguments集合。
箭头函数的特点:1.箭头函数的this是指向生产环境的,不是谁调用就指向谁。this的指向是由外层(函数或者全局)作用域来决定。
var box=document.getElementById("box")
box.onclick=function(){
//延时定时器 ,3s后
setTimeout(()=>{
console.log(this)
this.style.backgroundColor="blue"
},3000)
}
这段代码中的this就是指向box的,因为是局部作用域,
2.不存在函数的提升功能
3.无法作为构造函数
4.不存在arguments,rest参数 代替arguments