1、ES5类定义、静态方法、原型链的使用
1、ES5 里面的类、构造方法、属性、实例方法及静态方法
function Animal(name,age) {
this.name=name;
this.age=age;
//1.1、构造函数里面的方法
this.run=function () {
console.log(this.name+"正在跑...");
}
}
//1.2、原型链上添加方法
Animal.prototype.say=function(){
console.log("姓名:"+this.name+",年龄:"+this.age);
};
//1.3、静态方法,不需要实例对象调用,必须添加到类上
Animal.toString=function(){
console.log('这里是静态方法...');
};
//1.4、原型链上添加属性
Animal.prototype.birthday='11/29';
let taidi=new Animal("taidi",2);
console.log(taidi.age);
taidi.run();
taidi.say();
Animal.toString();
let caroon=new Animal("caroon",1);
caroon.birthday='5/6';
console.log(taidi.birthday);//11/29
console.log(caroon.birthday);//5/6
2、类继承
ES5 里面使用继承方法:
- 对象冒充继承
- 原型链继承
- 对象冒充+原型链继承(通常使用)
2.1、对象冒充继承
对象冒充继承只能够继承构造方法中的属性和方法,不能够继承原型链上的属性和方法
//2.1、对象冒充继承
function Animal(name,age) {
this.name = name;
this.age = age;
this.run = function () {
console.log(this.name + "正在跑...");
}
}
Animal.prototype.say=function(){
console.log("姓名:"+this.name+",年龄:"+this.age);
};
//对象冒充继承
function Bird(name,age) {
//对象冒充用call或apply
Animal.call(this,name,age);
}
let dayan=new Bird("dayan",1);
dayan.run();
//对象冒充继承只能够继承构造函数里面的属性和方法,原型链上属性和方法不能够继承
dayan.say();//报错
2.2、原型链继承
原型链继承可以继承属性和方法,但是没有办法给父类构造函数传参
function Animal(name,age) {
this.name = name;
this.age = age;
this.run = function () {
console.log(this.name + "正在跑...");
}
}
Animal.prototype.say=function(){
console.log("姓名:"+this.name+",年龄:"+this.age);
};
function Bird(name,age) {
}
// 原型链继承 2种写法
//Bird.prototype=Animal.prototype;
Bird.prototype=new Animal();
//方法和属性可有继承,但是没有办法给父类构造函数传参
let dayan=new Bird("dayan",1);
dayan.run();
dayan.say();// 姓名:undefined,年龄:undefined
2.3、通常采用对象冒充+原型链继承
function Animal(name,age) {
this.name = name;
this.age = age;
this.run = function () {
console.log(this.name + "正在跑...");
}
}
Animal.prototype.say=function(){
console.log("姓名:"+this.name+",年龄:"+this.age);
};
function Bird(name,age) {
//对象冒充继承
Animal.apply(this,[name,age]);
}
// 原型链继承 2种写法
//Bird.prototype=Animal.prototype;
Bird.prototype=new Animal();
//方法和属性可有继承,但是没有办法给父类构造函数传参
let dayan=new Bird("dayan",1);
dayan.run();
dayan.say();// 姓名:undefined,年龄:undefined