es5继承
2019-11-21 本文已影响0人
Wrestle_Mania
- 对象冒充实例继承(无法获取原型链上的属性和方法)
function Person(name, age) {
this.name = name;
this.age = age;
this.run = function() {
console.log(`${this.name}--${this.age}`);
};
}
Person.prototype.sex = "男";
Person.prototype.work = function() {
console.log(`${this.name}的性别是${this.sex}`);
};
// 对象冒充实例继承
// 能继承构造函数中的属性和方法,但是不能继承原型链上的属性和方法
function Web(name, age) {
Person.call(this, name, age);
}
const web = new Web("JonSnow", 21);
console.log(web.name); //JonSnow
console.log(web.sex); //undefined
web.run();
web.work(); //报错
- 原型链继承(实例化无法给父类传参)
function Person(name, age) {
this.name = name;
this.age = age;
this.run = function() {
console.log(`${this.name}--${this.age}`);
};
}
Person.prototype.sex = "男";
Person.prototype.work = function() {
console.log(`${this.name}的性别是${this.sex}`);
};
function Web(name, age) {}
Web.prototype = new Person();
const web = new Web("JonSnow", 21);
console.log(web.name); //undefined
console.log(web.sex); //男
web.run(); //undefined--undefined
web.work(); //undefined的性别是男
- 二者结合,实现继承
function Person(name, age) {
this.name = name;
this.age = age;
this.run = function() {
console.log(`${this.name}--${this.age}`);
};
}
Person.prototype.sex = "男";
Person.prototype.work = function() {
console.log(`${this.name}的性别是${this.sex}`);
};
function Web(name, age) {
Person.call(this, name, age);
}
Web.prototype = new Person();
const web = new Web("JonSnow", 21);
console.log(web.name); //JonSnow
console.log(web.sex); //男
web.run(); //JonSnow--JonSnow
web.work(); //JonSnow的性别是男