而JavaScript虽不是一门户严格意义上的面向对象语言,但,它也可以有自己的面向对象实现。
当然包括抽象。
在JavaScript中,虚方法可以看作该类中没有定义的方法,但已经通过this指针使用了.
通过下面的示例可以看出:
1
var tmp=function()
2
{
3
{
4
this.ini.apply(this,arguments);
5
//这里的arguments是构造函数的
6
//this.ini通过this调用,但却是未定义的。
7
//将在其prototype中给出实现
8
}
9
}
10
//实现虚方法 ini,且提供给构造函数调用
11
tmp.prototype.ini=function()
12
{
13
alert(arguments[0]);
14
}
15
var tt=new tmp('a');
在prototype.js中,对抽象类及类的创建有一段经典的实现:
如下:
![](/Images/OutliningIndicators/None.gif)
2
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
3
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
4
![](/Images/OutliningIndicators/InBlock.gif)
5
![](/Images/OutliningIndicators/InBlock.gif)
6
![](/Images/OutliningIndicators/InBlock.gif)
7
![](/Images/OutliningIndicators/InBlock.gif)
8
![](/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
9
![](/Images/OutliningIndicators/ExpandedBlockEnd.gif)
10
![](/Images/OutliningIndicators/None.gif)
11
![](/Images/OutliningIndicators/None.gif)
12
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
13
![](/Images/OutliningIndicators/InBlock.gif)
14
![](/Images/OutliningIndicators/ExpandedBlockEnd.gif)
15
![](/Images/OutliningIndicators/None.gif)
在prototype.js中,对抽象类及类的创建有一段经典的实现:
如下:
1 var Class=
2 {
3 create:function()
4 {
5 return function() //返回一个匿名函数,也就是一个函数对象
6 {
7 this.ini.apply(this,arguments); //此时的arguments是函数对象的构造函数传递过来的参数对象
8 }
9 }
10 }
11
12 var tmp=Class.create();
13
14 //此时tmp相当于
15 //var tmp=function()
16 //{
17 // this.ini.apply(this,arguments);
18 //}
19 //可以通过alert(tmp.toString());看出
20 tmp.prototype.ini=function()
21 {
22 alert(arguments.length); //这里的arguments是ini自身的参数
23 }
24 var ttt=new tmp('adf');
因为掉入了面向对象的泥潭,导致对Class.create居然久久不能明了
很汗,一个简单的返回匿名函数居然将我迷糊了很久。
因此如上代码记录在此,以作备忘
2 {
3 create:function()
4 {
5 return function() //返回一个匿名函数,也就是一个函数对象
6 {
7 this.ini.apply(this,arguments); //此时的arguments是函数对象的构造函数传递过来的参数对象
8 }
9 }
10 }
11
12 var tmp=Class.create();
13
14 //此时tmp相当于
15 //var tmp=function()
16 //{
17 // this.ini.apply(this,arguments);
18 //}
19 //可以通过alert(tmp.toString());看出
20 tmp.prototype.ini=function()
21 {
22 alert(arguments.length); //这里的arguments是ini自身的参数
23 }
24 var ttt=new tmp('adf');
因为掉入了面向对象的泥潭,导致对Class.create居然久久不能明了
很汗,一个简单的返回匿名函数居然将我迷糊了很久。
因此如上代码记录在此,以作备忘