当前位置: 首页 > 图文教程 > 网络编程 > Javascript > 关于Javascript 的 prototype问题。

Javascript
form中限制文本字节数js代码
use jscript with List Proxy Server Information
use jscript List Installed Software
List Installed Software Features
List Information About the Binary Files Used by an Application
List the Codec Files on a Computer
List the UTC Time on a Computer
List Installed Hot Fixes
excel操作之Add Data to a Spreadsheet Cell
Add Formatted Data to a Spreadsheet
Apply an AutoFormat to an Excel Spreadsheet
JavaScript语法着色引擎(demo及打包文件下载)
类之Prototype.js学习
一款JavaScript压缩工具:X2JSCompactor
iis6+javascript Add an Extension File
jscript之Open an Excel Spreadsheet
jscript之Read an Excel Spreadsheet
jscript之List Excel Color Values
去除图像或链接黑眼圈的两种方法总结
Add a Formatted Table to a Word Document

关于Javascript 的 prototype问题。


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-12   浏览: 147 ::
收藏到网摘: n/a

prototype
1、
prototype是与Clone联系起来的,
也就是说,当创建实例时,prototype会把成员clone到该Class(function)的实例上。
Detail: 最常见的几个内置内对象里的prototype,如:Array原型有join, split方法,
当创建数组a时var a=[1,2],原型里的所有方法都被clone到a上。
2、this是该类的实例指针(该指针为"动态联编")。如何理解js this的动态联编,请参考我写的这篇文章:http://blog.never-online.net/article.asp?id=117
当创建该类实例时,实例具有预先定义的所有以this.p类似的成员。也具有prototype原型里定义的成员,如果类内部定义与prototype里的一个定义相同,则不是重写:
看这个例子,jsclass定义的this.func,还有prototype里定义的func,如果jsclass内部有成员与原型里的相同,实例化时优先权为this.func,但注意,原型里并不是重写func,而是jsclass实例共有的,虽然其优先权没有this.func高,与此同时,我们也可以以这种方式来理解prototype与类内部定义成员:
<script>
function jsclass() {
this.p = "never-online";
this.func = function () {
alert('func');
}
}
jsclass.prototype = {
func : function () {
alert(this.p);
}
}
var a = new jsclass();
a.func();
delete a.func;
a.func();
</script>
我们再把上面的代码修改一下。这样看:
<script>
function jsclass() {
this.p = "never-online";
this.func = function () {
alert('func');
}
}
jsclass.prototype = {
func : function () {
alert(this.p?this.p:'no value');
}
}
var a = new jsclass();
a.func();//调用内部成员
delete a.func;//此处删除是的类内部定义的func
a.func();//调用prototype成员
delete a.func;//试图再次删除func(prototype)
a.func();//删除无效(内部的func已经被删除),依然可打印输出
</script>
注释:类内部的成员可以用delete删除,而原型里定义的,则不能用delete 实例名.成员名来删除的。
如果用prototype定义后,实例化时:用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象
也就是在上面的
delete a.func;//此处删除是的类内部定义的func
a.func();//调用prototype成员
之后,再次调用a.func(),调用时,通过调用prototype.func来实现的。而并非a.func(),这也解释了为什么在jsclass内部定义func与在prototype定义func时不会有重写现象。