继承和创建都展示五种
JS的继承模式
原型链继承
//定义父类
function Father(name,age){
this.name=name;
this.age=age;
}
//为父类原型添加方法
Father.prototype.say=function(){
console.log(this.name+this.age+"岁了,喜欢"+this.hobby);
}
//定义子类
function son(name,age,hobby){
this.name=name;
this.age=age;
this.hobby=hobby;
}
//创建父类型的对象将值赋给子类型的原型
son.prototype=new Father();
//修正子类原型中的constructor属性
son.prototype.constructor=son;
//实例化对象
var oneSon=new son("张三",13,"打篮球");
//调用方法
oneSon.say();
构造函数继承
//定义父类
function animal(name,age){
this.name=name;
this.age=age;
}
//定义子类
function cat(name,age,color){
//使用父类型中声明的变量
animal.call(this,name,age);
this.color=color;
}
//建立子类型的实例化对象
let c1=new cat("小白",3,"黑色")
console.log(c1.name+"是一只"+c1.age+"岁的"+c1.color+"小猫");
组合继承
//定义父类
function Bird(name,age){
this.age=age;
this.name=name;
}
//为父类添加方法
Bird.prototype.say=function(){
console.log(this.name,this.age,this.color)
}
//定义子类
function bugu(name,age,color){
Bird.call(this,name,age);
this.color=color;
}
bugu.prototype=new Bird()
bugu.prototype.constructor=bugu
var bu=new bugu("小布谷",1,"黄色");
bu.say()
原型式继承
function parents(name,age){
this.age=age;
this.name=name;
}
parents.prototype.say=function(){
console.log(this.age+"岁的"+this.name+"喜欢"+this.hobby)
}
//定义子类
function child(name,age,hobby){
parents.call(this,name,age);
this.hobby=hobby;
}
child.prototype=Object.create(parents.prototype)
child.prototype.constructor=child
var child1=new child("小明",16,"看书")
child1.say()
类继承
//定义父类
class teacher{
constructor(name,age){
this.name=name;
this.age=age;
}
//为父类型设置方法
say(){
console.log(this.name,this.age,this.doing)
}
}
//定义子类
class students extends teacher{
constructor(name,age,doing){
super(name,age);
this.doing=doing;
}
}
var stu=new students("小红",15,"听音乐")
stu.say()
创建模式
Object构造函数模式
套路:先创建空Object对象,再动态添加属性、方法
适用场景:起始时不确定对象内部数据
问题:语句太多
var person = new Object()
person.name = 'Tom'
person.age = 15
person.setName = function (name) {
this.name = name
}
对象字面量模式
套路:使用{}创建对象,同时指定属性、方法
适用场景:起始时对象内部数据是确定的
问题:如果创建多个对象,有重复代码
var p = {
name: 'Tome',
age: 12,
setName: function (name) {
this.name = name
}
}
工厂模式
套路:通过工厂函数动态创建对象并返回
适用场景:需要创建多个对象
问题:对象没有一个具体的类型,都是Object
function createPerson(name, age) {
var obj = {
name: name,
age: age,
setName: function (name) {
this.name = name
}
}
return obj
}
自定义构造函数模式
套路:自定义构造函数,通过new创建对象
适用场景:需要创建多个类型确定的对象
问题:每个对象都有相同的数据,浪费内存
function Student(name, price) {
this.name = name
this, price = price
this.setName = function (name) {
this.name = name
}
}
var s = new Student('tom', 12)
构造函数+原型的组合模式
套路:自定义构造函数,属性在函数中初始化,方法添加到原型上
适用场景:需要创建多个确定的对象
function Student(name, price) {
this.name = name
this.price = price
}
Student.prototype.setNmae = function (name) {
this.name = name
}
var s = new Student('tom', 12)
这是几种继承模式和创建模式,接下来就要写第一次项目了,对我们目前来说确实是一种挑战。但万事开头难,总要试一下。
生活碎片
昨天参加了学院的宿舍文化节,没想到第一场拔河就碰上了实力相当的对手,好在前两局都赢了。进入半决赛的对手倒是没有那么难缠,也是两局胜出。三项游戏,我们宿舍全是第一,这就是实力!
但是今天早上整个人竟然是翻身疼醒的😓,腰也疼,小腿疼,胳膊疼,这就是拔河太用力的后遗症······