对象冒充实现继承
function Person(){
this.name = '张三' ;
this.age = 18
this.run = () =>{
alert(`我叫 ${this.name} `)
}
}
Person.prototype.sex = '男'
Person.prototype.work = ()=>{console.log('我在工作')}
function PersonTo (){
Person.call(this)
}
let one = new PersonTo()
console.log(one.name)//正确
console.log(one.work)//错误
对象冒充可以继承构造函数里面的属性和方法
对象冒充不可以继承原型链上的属性和方法
重要部分
function PersonTo (){
Person.call(this)
}
原型链实现继承
function Person(){
this.name = '张三' ;
this.age = 18
this.run = () =>{
alert(`我叫 ${this.name} `)
}
}
Person.prototype.sex = '男'
Person.prototype.work = ()=>{console.log('我在工作')}
function PersonTwo(){
}
PersonTwo.prototype = new Person()
var two = PersonTwo.work()
var two1 = PersonTwo.run()
原型链可以继承构造函数和原型链里面的属性和方法
重要部分
PersonTwo.prototype = new Person()
分割部分
function Person(name,age){
this.name = '张三' ;
this.age = 18
this.run = () =>{
alert(`我叫 ${this.name} `)
}
}
Person.prototype.sex = '男'
Person.prototype.work = ()=>{console.log('我在工作')}
function PersonTwo(){
}
PersonTwo.prototype = new Person('王五', 20)
PersonTwo.run()//错误,打印是undefined在运动
原型链继承在实例化子类是没法给父类传参
构造函数和原型链实现继承
function Person(name,age){
this.name = '张三' ;
this.age = 18
this.run = () =>{
alert(`我叫 ${this.name} `)
}
}
Person.prototype.sex = '男'
Person.prototype.work = ()=>{console.log('我在工作')}
function PersonTwo(name ,age){
Person.call(this,name ,age)
}
PersonTwo.prototype = new Person('王五', 20)
//or
//PersonTwo.prototype = Person。prototype
PersonTwo.run()//正常,打印是王五在运动
构造函数和原型链可以继承构造函数和原型链里面的属性和方法,也可以在实例化子级的时候传参
重要部分
function PersonTwo(name ,age){
Person.call(this,name ,age)
}