JavaScript的Prototype实现
2010-09-14 13:18:27 来源:WEB开发网对象类的定义
function BookInfo(vCaption){
this.Caption=vCaption;
var curPage=0;
this.setPage=function(vData){
curPage=vData;
}
this.getPage=function(){
return curPage;
}
}
测试代码
//////////////////////////////////
//test BookInfo 's clone method
//
//////////////////////////////////
function test(){
var objTest=new BookInfo("javascript Prototype Pattern");
objTest.setPage(1000);
objTest.Author="Ruhong.Liu"; //object expanddo
ShowObject(objTest,"原始对象");
//Clone Object from objTest
var objCloned=objTest.Clone();
ShowObject(objCloned,"Clone之后的对象");
//if you changed the objTest's caption
//you can find objCloned's caption has be changed
objTest.Caption="Changed Base Object";
//show message
ShowObject(objTest,"修改Caption之后的原始对象");
ShowObject(objCloned,"修改Caption之后的clone对象");
/* //----------这段代码可以不工作------------------------//
//now you can change objCloned's caption objCloned.Caption="hello,Jeff.Yan"; //show message ShowObject(objTest,"Clone对象Caption修改之后的原始对象"); ShowObject(objCloned,"Clone对象Caption修改以后"); */
}
function ShowObject(o,vCaption){
var strMsg=vCaption +"n";
strMsg+="CurrentPage: " + o.getPage() +"n";
strMsg+="Caption: " + o.Caption +"n";
strMsg+="Expanddo Property Author: " + o.Author;
alert(strMsg);
}
结束语:
按照我目前的理解和测试,我觉得prototype关键字不是prototype模式的实现,这点通过parent object可以得到验证。
Tags:JavaScript Prototype 实现
编辑录入:爽爽 [复制链接] [打 印]更多精彩
赞助商链接