es5中类和静态方法、原型链继承
dearweb
发布:2021-07-25 11:20:54阅读:
对象冒充可以继承构造函数里面的属性和方法 但是没法继承原型链上面的属性和方法
对象冒充实现继承
// es5里面的继承
function Person(){
this.name = '武汉'
this.age = 20
this.run=function(){
console.log(this.name+'在跑步')
}
}
Person.prototype.sex= '女'
Person.prototype.work= function(){
console.log(this.name + '在工作')
}
// web类 继承Person类 原型链+对象冒充组合继承模式
function Web(){
Person.call(this); // 对象冒充继承
}
let w = new Web();
// w.run() // 对象冒充可以继承构造函数里面的属性和方法
w.work(); // 对象冒充可以继承构造函数里面的属性和方法 但是没法继承原型链上面的属性和方法es5中的静态方法继承
// es5中静态方法
function Person(){
this.name = '武汉'
this.age = 20
this.run=function(){
console.log(this.name+'在跑步')
}
}
Person.address = '湖北武汉'
let P = new Person()
console.log(P.address) // undefined
console.log(Person.address) // 湖北武汉原型链继承方法(既可以继承构造函数的属性和方法也可以继承原型链上的属性和方法)
// es5里面原型链的继承
function Person(){
this.name = '武汉'
this.age = 20
this.run=function(){
console.log(this.name+'在跑步')
}
}
Person.prototype.sex= '女'
Person.prototype.work= function(){
console.log(this.name + '在工作')
}
function Web(){
}
Web.prototype = new Person() // 原型链实现继承
let w = new Web()
w.work() // 武汉在工作原型链继承的问题(实例化子类的时候没法父类传参)
// es5里面原型链的继承的问题
function Person(name,age){
this.name = name
this.age = age
this.run=function(){
console.log(this.name+'在跑步')
}
}
Person.prototype.sex= '女'
Person.prototype.work= function(){
console.log(this.name + '在工作')
}
function Web(name,age){
}
Web.prototype = new Person() // 原型链实现继承
let w = new Web('王五',18)
w.work() // undefined在工作原型链+构造函数的集成方法
// 原型链+构造函数组合继承模式
function Person(name, age) {
this.name = name
this.age = age
this.run = function () {
console.log(this.name + '在跑步')
}
}
Person.prototype.sex = '女'
Person.prototype.work = function () {
console.log(this.name + '在工作')
}
function Web(name, age) {
Person.call(this,name,age)
}
Web.prototype = new Person()
let w = new Web('王五',18)
w.run() // 王五在跑步
w.work() // 王五在工作原型链+构造函数的集成方法(另一种写法)
function Person(name, age) {
this.name = name
this.age = age
this.run = function () {
console.log(this.name + '在跑步')
}
}
Person.prototype.sex = '女'
Person.prototype.work = function () {
console.log(this.name + '在工作')
}
function Web(name, age) {
Person.call(this,name,age)
}
Web.prototype = Person.prototype // 直接继承原型链
let w = new Web('王五',18)
w.run() // 王五在跑步
w.work() // 王五在工作小礼物走一波,支持作者
赏还没有人赞赏,支持一波吧