对于js原型和原型链继承的简单理解(第二种,对象冒充)

时间:2023-03-09 00:12:09
对于js原型和原型链继承的简单理解(第二种,对象冒充)

关键代码    this.parent = Cat;    this.parent.apply(this);

              function Cat(){
this.climb = function(){
alert("我会爬树");
}
}
var cat = new Cat();
cat.climb(); function Dog(){
this.parent = Cat;
this.parent.apply(this);//当然也可以传参,
this.eat = function(){
alert("我会吃");
}
}
var dog = new Dog();
console.log(dog)
dog.climb();

会输出两个我会爬树,这应该就是所谓的对象冒充吧,Dog通过parent切切实实的拥有了爬树的climb方法

与原型链的区别就是:原型链是顺着链进行查找这个方法,而对象冒充是拥有了这个方法