一、类的定义与实例化
es5中怎么声明一个类
//将所有的方法都放在构造函数中,会是得每一个实例都会很大
let Animal = function (type) {
this.type = type
this.eat = function () {
}
}
let dog = new Animal ('dog')
let Animal = function (type) {
this.type = type
}
//如果把eat方法放在构造函数中,相当与在每一个实例中对eat做了一个备份,每个备份都不相互互通。
Animal.prototype.eat = function () {
console.log('eat food')
}
let dog = new Animal ('dog')
//修改eat方法会修改到其他实例eat方法(共同的eat方法)
dog.constructor.prototype.eat = function () {
console.log('error')
}
dog.eat()
es6怎么定义类
class Aniaml {
//constructor是一个构造函数,在构造函数中写属性
constructor(type){
this.type=type
}
//在构造函数外写方法,方法会写在原型链路中
eat(){
console.log('eat food')
}
}
let dog = new Animal ('dog')
二、静态方法
注释:静态方法是属于类的,要通过类名进行调用
es5中定义静态方法与使用静态方法
let Animal = function (type) {
this.type = type
}
Animal.prototype.eat = function () {
//调用静态方法
//注释:实例方法是通过实例化来调用的,静态是通过类名直接调用。
Animal.walk()
console.log('eat food')
}
//定义静态方法
Animal.walk = function () {
console.log('walking')
}
let dog = new Animal ('dog')
es6中的定义静态方法与使用静态方法
class Aniaml {
constructor(type){
this.type=type
}
eat(){
//调用静态方法,还是通过类名进行引用
Aniaml.walk()
console.log('eat food')
}
//es6中有专门的方法来识别是静态方法还是实例的方法
static walk(){
console.log('walking')
}
}
let dog = new Animal ('dog')
三、es5与es6的继承
es5的继承
构造函数、原型和实例的关系:每一个构造函数都有一个原型对象,每一个原型对象都有一个指向构造函数的指针,而每一个实例都包含一个指向原型对象的内部指针
let Animal = function (type) {
this.type = type
}
Animal.prototype.eat = function () {
console.log('eat food')
}
//子类继承父类
let Dog = function (){
//初始化父类的构造函数,是this指向dog
Animal.call(this,'dog')
this.run = function () {
console.log('run')
}
}
//继承父类的原型链
Dog.prototype = Animal.prototype
let dog = new Dog('dog')
dog.eat()
es6的继承
class Aniaml {
constructor(type){
this.type=type
}
eat(){
console.log('eat food')
}
}
class Dog extends Animal {
constructor (type){
//super要写在新添加的属性前,不然会报错
super(type)
this.age = 2
}
}
let dog = new Dog ('dog')
dog.eat()
四、函数参数默认值设置
es5的参数默认值
function add (x,y,z){
if(y===undefined){
y=1
}
if(z===undefined){
z=2
}
return x+y+z
}
es6参数的默认值
//在写参数的时候就设置了默认值,设置了y的默认值是7,z的默认值是8
//注意:参数的默认值可以是其他参数组成的表达式 比如z=x+y
function add (x,y=7,z=8){
return x+y+z
}
//如果没有传入的参数则要使用undefined
console.log(f(1,undefined,43))