js 继承和原型链
1.对象
<script>
function Car(name,speed){
this.name=name;
this.speed=speed;
}
Car.prototype.showName=function(){ //独立出来的公共空间,减少内存
console.log(this.name);
}
var car=new Car("奥迪",300); //new创建新空间,每次new都会复制name,speed
var car2=new Car("奔驰",280);
console.dir(car); //输出结构
console.dir(car2);
car.showName(); //调用showName()方法
</script>


2.继承
<script>
//把Student()和People()建立关系--》让Student()间接调用People()里的showName
function People(name){
this.name=name;
}
People.prototype.showName=function(){
console.log(this.name);
}
function Student(){
}
Student.prototype=new People("德尔");//把Student.prototype给People()
Student.prototype.study=function(){
console.log("学习");
}
var stu=new Student();
// stu.study();
// stu.showName();
//原型链 实现继承 原型链的最终指向是object,object的原型是null
//console.dir(stu.__proto__===Student.prototype);
//console.dir(Student.prototype.__proto__===People.prototype);
// console.dir(stu.__proto__.__proto__===People.prototype);
// console.dir(People.prototype.__proto__.__proto__);
console.dir(stu.__proto__.__proto__.__proto__.__proto__);
//对象的原型 __proto__
//构造函数的原型 prototype
</script>


浙公网安备 33010602011771号