首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > JavaScript >

JavaScript中prototype/constructor的了解

2012-10-24 
JavaScript中prototype/constructor的理解一,prototype(对象)(原型链)可使javascript拥有1,重写2,添加方法

JavaScript中prototype/constructor的理解

一,prototype(对象)(原型链)

可使javascript拥有

1,重写

2,添加方法

3,继承的机制

?

prototype继承原理:

每一个方法的创建,都有着一个单例的对象functionName.prototype, 在使用这个方法创建的每一个对象,该prototype都会赋值给他,(prototype里面包含了一些属性,方法包含construtor)

也正因为每个对象都共享一个prototype,所以可以操作这个prototype,

1,将你类对象赋给他达到继承的目的,看下面文章

2,可在该prototype上,重写方法,或者添加方法

?

1,重写

//为了达到封装的完善性,引申以下问题//引申问题一,保证使每一个对象object.construcotr能够找到自己(function)//引申问题二,保证使之通过suberObject能找到父类//问题一例子function Parent(){this.log=function(){document.writeln("this is parent log.....<br>");}}function Suber(){this.log=function(){document.writeln("this is suber log......<br>");}}var suber1=new Suber();//可得到子类本身document.writeln(suber1.constructor);//故当其中有一个被改变时,另一个也会被改变.construcotr是相应的prototype中的一个属性,以下访问是同一个属性document.writeln(suber1.constructor===Suber.prototype.constructor);document.writeln("<br>--------------------------------------------<br>");//当继承时.....Suber.prototype=new Parent();var suber2=new Suber();//得到的是父类本身,丢失了自己的构造函数,故"问题一"出现document.writeln(suber2.constructor);document.writeln("<br>--------------------------------------------<br>");//解决"问题一"方法Suber.prototype=new Parent();Suber.prototype.constructor=Suber;var suber3=new Suber();document.writeln(suber3.constructor);document.writeln("<br>--------------------------------------------<br>");//这样一来,引申出"问题二",我们获取不到parent的本身方法//故只能采用定义一个属性的方式来存储父类//解决"问题二"方法Suber.prototype=new Parent();Suber.superClass=Parent;//每一级别都设置该属性进行存储父类方法Suber.prototype.constructor=Suber;var suber4=new Suber();document.writeln(suber4.constructor);document.writeln("<br>--------------------------------------------<br>");document.writeln(Suber.superClass);
?

//可参考extjs中的继承封装....

?

参考文章:http://hi.baidu.com/maxwin2008/blog/item/8da86102c1ceda034bfb51a3.html

热点排行