原型模式:每创建一个函数都有一个prototype属性,它是一个指针,指向一个对象;
原型模式创建函数的方式:
function Movie(){ };
Movie.prototype.name="Interstellar";
Movie.prototype.year=2014;
Movie.prototype.country="American";
Movie.prototype.playMovie=function(){
alert(this.name);
} var movie1=new Movie();
movie1.playMovie();//Interstellar;
var movie2=new Movie();
movie2.playMovie();//Interstellar; alert(movie1.playMovie==movie2.playMovie);//true 有别于构造函数
对象字面量的方式
function Movie(){ };
Movie.prototype={
name:"Interstellar",
year:2014,
country:"American",
playMovie:function(){
alert(this.name);
}
}
//这种方式原型对象的contructor属性不会指向Movie了,而是指向Object了。
每当代码读取某个属性时,都会先搜索对象实例本身,没有就继续搜索指针指向的原型对象,如果有就结束;通过hasOwnProperty()可以检测属性是存在实例中还是原型中:
function Movie(){
};
Movie.prototype.name="FleetOfTime";
Movie.prototype.year=2014;
Movie.prototype.country="China";
Movie.prototype.playMovie=function(){
alert(this.name);
}
var movie1=new Movie();
alert(movie1.hasOwnProperty("name"));//原型上的 false
movie1.name="xxxx";
alert(movie1.hasOwnProperty("name"));//覆盖了原型上的,变成实例上的了 true
原型的动态性:对原型对象所做的任何修改都能够立即从实例中反映出来,例:
var movie=new Movie();
Movie.prototype.playOne=function(){
alert("One");
};
movie.playOne();//"One" //给Movie原型对象添加了一个方法
但是如果是重写整个原型对象的话,那么就等于切断了构造函数与最初原型之间的联系了:
function Movie(){ } var movie=new Moive();
//重写原型对象
Movie.prototype={
constructor:Movie,//对象字面量方式强制指向Movie,本来指向Object
name:"xxx",
year:2012,
country:"xxxx",
sayName:function(){}
}
//这时候调用sayName()方法会出错
movie.sayName();//error
原型对象的问题:对于包含引用类型值的属性来说,就有很大问题了,如下例子
function Movie(){
}
Movie.prototype={
constructor:Movie,
name:"xxx",
year:2014,
place:["China","Japan"],
playName:function(){
alert(this.name);
}
}
var movie1=new Movie();
var movie2=new Movie(); movie1.place.push("korea"); alert(movie1.place)//"China,Japan,Korea" alert(movie2.place)//"China,Japan,Korea" //这里本来是想只改变movie1的place,结果也改到了movie2的
最好的创建对象方式:构造函数来定义实例属性,原型模式来定义方法和共享属性;
function Movie(name,year,country){
this.name=name;
this.year=year;
this.country=country
this.place=["China","Japan"];
}
Movie.prototype={
constructor:Movie,
playName:function(){
alert(this.name);
}
} var movie1=new Movie("Interstellar",2014,"American");
var movie2=new Movie("FleetOfTime",2014,"China");
movie1.place.push("Korea");
alert(movie1.place);//"China,Japan,Korea"
alert(movie2.place);//"China,Japan" alert(movie1.place==movie2.place);//false
alert(movie1.playName==movie2.playName);//true