当前位置: 首页 > 图文教程 > 网络编程 > Javascript > JS类中定义原型方法的两种实现的区别

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 中的 JS类中定义原型方法的两种实现的区别


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

我们知道,给JavaScript类添加原形(prototype)方法是很简单的。而且常用的有下面这两种方法,可是这两种方法在使用时有区别吗?
JScript Class:
function JSClass()
{
}
Extends prototype method:
JSClass.prototype.MethodA = function()
{
};
Or
function = JSClass.prototype.MethodA()
{
};
其实这两个原形定义方式可以简化一下来讨论,先把它们看作是两个函数,如下:
Foo1();
function Foo1()
{
alert(’This is Foo1.’);
}
和 Foo2();
var Foo2 = function()
{
alert(’This is Foo2.’);
}
运行第一个显然是不会有任何错误的,可是运行第二个就有问题了,这时系统会说:Microsoft JScript runtime error: Object expected。这就是说函数定义(Foo1)在脚本解析器中有最高的初始化优先级,这个很好理解。如果不优先处理函数,那么对于函数中的函数调用就没有办法处理了,假使我们先定fn1()再定义fn2(),却从fn1中调fn2,那么就通不过解析了。为什么Foo2不能被初始化,Foo2的定义根本不是函数定义,它是一个标准的赋值语句,之所以能象标准函数一样的使用Foo2(Foo2()),完全是因为它指向的是一个函数对象的实例而已。
再来看原形方法导入里的两种方式,就很简单了。并且不同的执行优先循序,也决了它们在使用中的不同,看如下示例:
<script language="javascript">
function NormalClass()
{
this.m_Property1 = ’P1 in Normal Class.’;
this.m_Property2 = ’P2 in Normal Class.’;
this.toString = function()
{
return ’[class NormalClass]’;
}
return new InnerClass();
function InnerClass()
{
this.m_Property1 = ’P1 in Inner Class.’;
this.m_Property2 = ’P2 in Inner Class.’;
this.toString = function()
{
return ’[class InnerClass]’;
}
}
InnerClass.prototype.Method1 = function()
{
alert(this.m_Property1);
};
function InnerClass.prototype.Method2()
{
alert(this.m_Property2);
};
}
</script>
执行:
var nc = new NormalClass();
nc.Method1();
nc.Method2();
是什么效果?为什么?