es5面向对象
在es6之前,js的函数和对象是混在一起的,通过new调用函数,就是把函数当作对象,创建实例。
funciton Person(name,age){
this.name = name
this.age = age
}
Person.prototype.getName = function(){ return this.name }
Person.prototype.setName = function(name) { this.name = name }
var p = new Person('张三',13)
p.setName('xxx')
var name = p.getName()
1)属性定义在函数中,每个实例对象不同
2)方法定义在原型上,实例对象共享
ES6面向对象
ES6引入了class、constructor可以明确定义类
class Person(){
constructor(name,age){
this.name = name
this.age = age
}
getName() {
return this.name
}
setName(name) {
this.name = name
}
}
使用class关键字定义类,属性定义在constructor中,方法定义在类中
ES5的继承
es5中继承是借用了父类构造函数和原型实现的
/*Student 继承 Person*/
function Student(name,age,lev){
Person.call(this,name,age)
this.lev = lev
}
Sub.prototype = Object.create(Super.prototype);
Student.prototype.constructor = Student
1)首先在子类中调用了父类的构造函数,并绑定为子类的this,这样让子类实例可以得到父类实例的属性
2)让子类的原型指向父类的原型,让子类实例可以拥有父类原型上定义的方法
3)修正原型的constructor 为子类构造函数
也可以这样继承原型:Student.prototype = new Person(),这样继承的原型"不干净",不仅继承到父类原型上的方法,也继承了父类实例的方法。
function Person(){
doSomething: function() { /*这是实例的方法*/ }
}
ES6的继承
ES6中class定义的类,可以通过extends实现继承,使用super调用父类构造函数,比ES5继承方便的多
class Student {
constructor(name,age,lev){
super(name,age)
this.lev = lev
}
getLev() {
return this.lev
}
}
细节详情参见:ES6-class继承

352

被折叠的 条评论
为什么被折叠?



