原型重写问题

(1)

function Aa(name){
  this.name = name;
  this.colors = ["red","blue","green"];
}

Aa.prototype.sayName = function(){
  console.log(this.name)
}
function Bb(name,age){
  Aa.call(this,name);
  this.age = age;
}
var b = new Bb()
// console.log(b.sayName)
console.log(Aa.prototype)


Bb.prototype.sayAge = function (){
  console.log(this.age)
}
Bb.prototype.ue="ni"

console.log(Bb.prototype)

未重写Bb.prototype原型前,Aa.prototype原型所包含的属性方法有一下这些:

未重写Bb.prototype原型前,Bb.prototype原型所包含的属性方法有一下这些:

同样这里,实例b也不能访问Aa的原型方法和属性

(2)

function Aa(name){
  this.name = name;
  this.colors = ["red","blue","green"];
}

Aa.prototype.sayName = function(){
  console.log(this.name)
}
function Bb(name,age){
  Aa.call(this,name);
  this.age = age;
}
var b = new Bb()
// console.log(b.sayName)
console.log(Aa.prototype)


Bb.prototype.sayAge = function (){
  console.log(this.age)
}
Bb.prototype.ue="ni"

console.log(Bb.prototype)

//重写Bb.prototype
Bb.prototype = new Aa();
Bb.prototype.constructor = Bb;
console.log(Bb.prototype)

 console.log(instance.ue)//undefined
instance.sayAge()//直接报错,说instance.sayAge is not a function

重写Bb.prototype后,Bb.prototype的属性和方法:将Aa构造函数的属性和原型的方法都继承过来了,但是替换前添加的Bb原型对象的方法和属性都将被重写,所以当Bb的实例instance访问Bb的原型属性ue是会打印出undefined

当访问sayAge是,会报错instance.sayAge is not a function

 总结:为了避免超类型构造函数不会重写子类型的属性,可以在调用超类型构造函数后,再添加应该再子类型中定义的属性和方法

猜你喜欢

转载自www.cnblogs.com/psxiao/p/11372163.html
今日推荐