继承
js没有类的概念,因此,js的继承不是通过类来实现的。
而是通过“原型”的概念来完成的
//老虎的构造函数
function Tiger(){
this.bark = function(){
alert('我是百兽之王');
}
}
var huzi = new Tiger();
/*以java为例,应该让Tigre继承Cat类,但js做不到。
那么如何让老虎有猫的属性呢? ==》照猫画虎
我们明确的对‘Tigre函数’指定,用某个具体的‘cat对象’做原型,并创建老虎对象。
*/
function Cat(){
this.climb = function(){
alert('我会爬树');
}
}
var bosi = new Cat();
huzi.bark();
bosi.climb();
//huzi.climb();//老虎没有爬树的方法。
//开始继承
Tiger.prototype = new Cat();//使用cat对象做原型,创建老虎对象。
var hnhu = new Tiger();
hnhu.climb(); // 老虎也有了爬树的方法
在这个继承的过程中发生了什么?
1.构造对象hnhu{}
2.hnhu.bark = function (){}
3.hnhu.proto=tiger.prototype //这是继承的关键。
就是说==》js中,每个对象都有一个__proto__指向其原型对象。
原型对象也是对象啊,也有__proto__
----原型的原型的原型的原型--是谁?//null
继承的解释
function cat(){
this.climb = function(){
alert('我会爬树');
}
}
console.log(cat.prototype);//空对象,显示为cat
console.log(cat.prototype.constructor);
//因为原型对象的constructor指向function cat(){}
console.log(cat.prototype.__proto__);//空对象object
console.log(cat.prototype.__proto__.__proto__);//null
继承练习
function pig(){
this.eat = function(){
alert('我能吃三十斤');
}
}
//在原型链上加上一个唱歌方法,系统的对象首字母大写Object
Object.prototype.sing = function(){
alert('出卖我的爱');
}
var zhu = new pig();
pig.sing();
腾讯继承面试题
function Dog(){
this.bark = function (){
alert('汪汪');
}
}
function peter(){
this.fire = function(){
alert('第一斗犬');
}
}
peter.prototype = new Dog();
var peter = new peter();
peter.bark();
function huzi(){
this.eat = function(){
alert('第一吃货');
}
}
huzi.prototype = new Dog();
huzi.prototype.bark = function(){
alert('呜呜');
}
var huzi = new huzi();
huzi.bark();
// 答案:汪汪 呜呜
// 如果构造函数peter的fire改为bark,结果又是如何?
答案:第一斗犬 呜呜
因此,以构造函数创建出来的对象,先在函数自身属性上查找属性,找不到再到原型链上去找。