//原型链继承
function Father(name,age){//构造器
this.name=name;
this.age=age;
this.say=function(){
console.log(this.name)
}
}
Father.prototype.walk=function(){//在对象原型对象上设置的方法
console.log(this.age)
}
function Son(){
this.jump=function(){
console.log(this)
}
}
Son.prototype=new Father()//此处为原型链继承,继承的是Father实例上的属性
var son1=new Son("zhangsan",18)
//以下两行代码可以验证son._proto_=Son.prototype
console.log(son1.__proto__)//{walk: ƒ, constructor: ƒ}
console.log(Son.prototype)//{walk: ƒ, constructor: ƒ}
console.log(Son.prototype.hasOwnProperty("age"))//true
console.log(Son.hasOwnProperty("age"))//false
console.log(Son.prototype.hasOwnProperty("walk"))
console.log(Father.hasOwnProperty("walk"))
console.log(Father.prototype.hasOwnProperty("walk"))
console.log(Father.prototype)//{walk: ƒ, constructor: ƒ}
//构造器继承
function Father(name,age){//构造器
this.name=name;
this.age=age;
this.say=function(){
console.log(this.name)
}
}
Father.prototype.walk=function(){//是在Farher原型对象上的方法
console.log(this.age)
}
function Son(sex){
//构造器继承 继承原型属性
Father.call(this);
this.sex=sex;
}
var son1=new Son()
console.log(Son.prototype)
console.log(Son.hasOwnProperty("age"))//false 实际上是在未来的将要创建的Son的实例的环境下面调用了Father构造函数
console.log(son1.hasOwnProperty("age"))//true
console.log(son1.hasOwnProperty("walk"))//false
console.log(Son.hasOwnProperty("walk"))//false
原型链继承和构造函数继承
最新推荐文章于 2022-03-08 15:16:17 发布