1、关于es5
es5中的类
// 1、最简单的类
function Person() {
this.name = "姓名";
this.age = 20;
}
let p = new Person();
console.log(p.name);
// 2、构造函数和原型链里面增加方法
function Person() {
this.name = "姓名"; // 属性
this.age = 20;
this.run = function () {
// 实例方法 通过new实例化之后才可以调用
console.log(this.name + "run");
};
}
// 原型链上面的属性会被多个实例共享 构造函数不会
Person.prototype.sex = "性别";
Person.prototype.work = function () {
console.log(this.name + "work");
};
let p2 = new Person();
p2.run();
Person.work;
静态方法
// 类里面的静态方法
Person.getInfo = function () {
console.log("我是静态方法");
};
// 调用静态方法
Person.getInfo();
继承
(1)对象冒充实现继承
function Person() {
this.name = "姓名"; // 属性
this.age = 20;
this.run = function () {
// 实例方法 通过new实例化之后才可以调用
console.log(this.name + "run");
};
}
Person.prototype.sex = "性别";
Person.prototype.work = function () {
console.log(this.name + "work");
};
// Web类 继承Person类 原型链 + 对象冒充的组合继承模式
function Web() {
Person.call(this); // 对象冒充实现继承
}
var w = new Web();
w.run(); // 对象冒充可以继承构造函数里面的属性和方法 但是没法继承原型链上面的属性和方法
w.work();
(2) 原型链实现继承 可以继承构造函数里面的属性和方法 也可以继承原型链上的属性和方法
function Web() {}
Web.prototype = new Person();
var w = new Web();
w.work();
// 原型链实现继承存在的问题:实例化子类的时候没法给父类传参
function Pro(name, age) {
this.name = name;
this.age = age;
this.run = function () {
// 实例方法 通过new实例化之后才可以调用
console.log(this.name + "run");
};
}
Pro.prototype.sex = "性别";
Pro.prototype.work = function () {
console.log(this.name + "work");
};
function Wpro(name, age) {}
Wpro.prototype = new Pro();
var w = new Wpro("我", 18);
w.run();
(3)原型链 + 构造函数 的 组合继承模式
function Merge(name, age) {
this.name = name;
this.age = age;
this.run = function () {
console.log(this.name + "run");
};
}
Merge.prototype.sex = "性别";
Merge.prototype.work = function () {
console.log(this.name + "work");
};
function Wmerge(name, age) {
Merge.call(this, name, age); // 对象冒充继承 可以继承构造函数里面的属性和方法 实例化子类可以给父类传参
}
组合继承也可以写为 Wmerge.prototype = Merge.prototype