JS 原型
原型介绍与使用
每一个构造函数被创建,系统都会自动创建一个与构造函数相对应的对象,
那么这个对象就是原型。
访问原型对象的方法, 构造函数名.prototype
function Student(name,age){
this.name=name;
this.age=age;
}
Student.prototype.sayHi=function(){
console.log("hello,我是"+this.name+",我来自湖北");
}
var s1=new Student("小明",24);
s1.sayHi();
console.dir(Student);
console.log(Student.prototype);
构造函数的原型是一个对象 既然是对象 那么可以往里面添加属性和方法
Student.prototype.type="children";
Student.prototype.read=function(){
console.log("我是"+this.name+",在读课文");
}
var s3=new Student("Tony",14);
console.log(s3.type);
s3.read();
往原型中添加的方法哪些可以访问
构造函数自己可以访问
console.log(Student.prototype.type);
该构造函数实例化出来的对象可以访问
var s3=new Student("Tony",14);
console.log(s3.type);
s3.read();
什么样的数据可以放进原型
该构造函数实例化出来的所有对象都共有的属性或者方法
function Student(name,age){
this.name=name;
this.age=age;
}
//因为每一个实例化对象都有一个sayHi的方法 而且执行的函数体一样 所以可以写进原型里
Student.prototype.sayHi=function(){
console.log("hello,我是"+this.name+",我来自湖北");
}
构造函数的原型是一个对象 既然是对象 那么可以往里面添加属性和方法
Student.prototype.type="children";
Student.prototype.read=function(){
console.log("我是"+this.name+",在读课文");
}
//共有的属性或者方法 指的是所有的实例化对象都有这个属性 并且属性都一样
Student.prototype.gender="女"
var s1=new Student("二狗",15);
console.log(s1.gender)//女
构造函数访问对象的规则
原型 :构造函数名.prototype
最先访问实例化对象自己的 如果没有 就访问构造函数里面的 如果还没有就访问原型里面的(就近原则)
function Dog(name,breed){
this.name=name;
this.breed=breed;
//构造函数内部的方法
this.sayHi=function(){
console.log("我是构造函数里面的sayHi方法");
}
}
//构造函数原型里面的
Dog.prototype.sayHi=function(){
console.log("汪汪汪,我是"+this.name);
}
var d1=new Dog("小白","博美");
d1.sayHi();
//实例化对象自己的 单个对象独有的方法
d1.sayHi=function(){
console.log("我是d1里面的sayHi方法");
}
d1.sayHi();
修改原型中的方法
访问原型 必须要使用 构造函数名.prototype
function Cat(name,age){
this.name=