原型this指向改变:
原型的this指向是可以改变的。我们知道实例对象的原型_proto_指向的是该对象所在的构造函数中的原型对象prototype,但是如果构造函数的原型对象(prototype)指向如果改变了,那么实例对象的原型(_proto_)也会改变。
案例:具体如下代码:
//人的构造函数
function Person(age){
this.age=10;
}
//人的原型对象方法
Person.prototype.eat=function(){
console.log("慢点吃");
};
//学生的构造函数
function Student(){
}
Student.prototype.sayHi=function(){
console.log("(。・∀・)ノ゙嗨,小苏您好帅哦");
}
//学生的原型,指向了一个人的实例对象
Student.prototype=new Person(10);
var stu=new Student();
stu.eat();//输出“慢点吃”
stu.sayHi();
//输出错误,原因是此时的实例对象是Person类型的,所以无法访问Student的原型方法
原型中的方法相互访问:
使用原型模式创建的实例对象,该对象具有的方法是可以相互访问的。
案例:具体如下代码:
function Animal(name,age){
this.name=name;
this.age=age;
}
//原型中添加方法
Animal.prototype.eat=function(){
console.log("动物吃东西");
this.play();
};
Animal.prototype.play=function(){
console.log("玩球");
this.sleep();
};
Animal.prototype.sleep=function(){
console.log("睡觉了");
};
var dog=new Animal("小苏",20);
dog.eat();//输出 动物吃东西, 玩球, 睡觉了