ES5的类创建方式
// 最简单的类function Person(name){ // 构造函数的属性 this.name = name; this.age = 18;}let xiaoming = new Person('小明');console.log(`${xiaoming.name}今年${xiaoming.age}岁`);// 构造函数 原型链上增加方法function Animal(name="小白"){ // 构造函数的属性 this.name = name; this.obj = { name : this.name } // 构造函数的方法 this.run = function(){ console.log(`${this.name}在奔跑!` ); }}// 原型链上的属性Animal.prototype.sex = '男';// 原型链上的方法Animal.prototype.cry = function(v){ // 传值 console.log(`调用原型链上的方法并且 - ${v}`); // 直接调用构造函数的属性 console.log(`得到构造函数的属性${this.name} ${this.obj}`);}let dog = new Animal('大白');console.log(dog.name);dog.run()console.log(dog.obj.name);console.log(dog.sex);// 调用方法后可以传值dog.cry('传值')
ES5继承
function Person(name,sex) {
// 构造函数的属性
this.name = name;
this.age = 18;
this.sex = sex
this.run = function (age) {
console.log(this.name, age,this.sex);
}
}
Person.prototype.dog = function () {
// 原型对象获取构造函数的属性
console.log(this.name, this.age);
}
const ming = new Person('小明','男')
ming.run(18)
ming.dog()
// 1、原型链+对象冒充的组合继承模式,web类继承Animal类,
function Web(nameVal,sexVal){
// 这里需要接受一个参数 才能使用构造函数的形参
Person.call(this,nameVal,sexVal) // 点睛之笔
}
const w = new Web('小红','女');
w.run(1);//只能调用构造函数自己的属性方法。原型链上的无法调用(报错);
// 2、原型链继承
function Inherit(){};
// 通过原型链来继承
Inherit.prototype = new Person('小环','女'); //..构造函数的形参传值
const In = new Inherit();
In.run(18) // 继承构造函数的方法;
In.dog() // 继承构造函数的方法;