Es5中的类

es5中的类语法:
简单案例:
function Person(){ //构造函数
this.name="Josie";
this.age=12
}
var p = new Person()
console.log(p.name)----输出 Josie

若在构造函数与原型链中添加方法

//构造函数中添加方法
function Person(){
this.name="Josie";
this.age=12;
this.work=function(){
console.log(${this.name} is working)
}
}
var p = new Person();
p.working() //输出 Josie is working.
//通过原型链定义属性或方法
Person.prototype.gender="female"
Person.prototype.run=function(){
console.log(this.name+' is running')
}
var p = new Person();
p.run() //输出 Josie is running
附:原型链上面的属性会被多个实例共享,构造函数不会,通过new的都是实例方法,即实例函数

类里面的静态方法
Person.getInfo = function () {
console.log('静态方法,不需要new Person()实例,也不需要再Person方法中定义该方法或者原型链定义该方法')
}
调用静态方法:
Person.getInfo()

es5 中的继承---------原型链+对象冒充的组合继承模式
function Animal(){
this.name="kitten";
this.age=1;
this.food=function(){
console.log(${this.name} loves eating fish)
}
}
Animal.prototype.catch=function(){
console.log(${this.name} can catch mice)
}
function Cat(){
Animal,call(this) ----对象冒充
}
var c= new Cat();
console.log(c.name) //输出Kitten
console.log(c.food()) //输出Kitten loves eating fish
console.log(c.catch()) //输出 c.catch() is not a function
结论:对象冒充可以继承构造函数里面的属性和方法,但是不能继承原型链上面的属性和方法

es5 中的继承---------原型链继承模式
function Animal(){
this.name="kitten";
this.age=1;
this.food=function(){
console.log(${this.name} loves eating fish)
}
}
Animal.prototype.catch=function(){
console.log(${this.name} can catch mice)
}
function Cat(){}
Cat.prototype = new Animal()
var c = new Cat()
console.log(c.name) //输出 kitten
console.log(c.food()) //输出Kitten loves eating fish
console.log(c.catch()) //输出 kitten can catch mice
结论:原型链实现继承,可以继承构造函数里面的属性和方法,也可以继承原型链上的属性和方法
原型链实现继承存在的问题---如果要传递参数,实例化子类的时候,不能给父类传参--------------------
案例:
function PersonalInfo(name, age) {
this.name = name;
this.age = age
this.working = function () {
console.log(this.name + ' is working')
}
}
PersonalInfo.prototype.gender = "male"
PersonalInfo.prototype.doing = function () {
this.name + 'is doing sth'
}
function Web(name, age) { }
Web.prototype=new PersonalInfo();
var p1 = new Web('abc', 20);
console.log(p1.name) //1.结果是undefined,能继承,但是不能传参,abc传递失败.
-------若需实现参数的传递,则需要结合对象冒充
function PersonalInfo(name, age) {
this.name = name;
this.age = age
this.working = function () {
console.log(this.name + ' is working')
}
}
PersonalInfo.prototype.gender = "male"
PersonalInfo.prototype.doing = function () {
this.name + 'is doing sth'
}
function Web(name, age) {
PersonalInfo.call(this, name, age) //加入对象冒充,且参数另外写
}
Web.prototype=new PersonalInfo();
var p1 = new Web('abc', 20);
console.log(p1.working()) //输出 abc is working 实现参数的传递

原文地址:https://www.cnblogs.com/jocelyn11/p/14421525.html