如何使用prototype.js创建一个类
问题描述:
任何人都可以使用prototype.js创建一个类,以及它是如何工作的。任何人都可以为prototype.js以外的其他官方站点提供很好的示例和教程吗?如何使用prototype.js创建一个类
答
创建PrototypeJS类与在正常的OOP语言中创建类非常相似。现在的方法来填充它,如果你把一个方法initialize
PrototypeJS就会触发作为构造
var myClass = Class.create(
{
initialize : function()
{
this.options = 0;
}
});
-
首先通过命名类
var myClass = Class.create({ });
这将创建一个空的类开始
你可以在默认值initialize()
方法中设置任何你想要的或者只是初始化类的属性。让我们加入其他一些方法,并展示如何实例化类。
var myClass = Class.create(
{
initialize : function()
{
this.options = 0;
},
testme : function()
{
this.options++;
},
showme : function()
{
alert(this.options);
return this.options;
}
});
var theClass = new myClass();
让我们再来一步,调用方法中的其他方法,并将选项传递给构造函数。
var myClass = Class.create(
{
initialize : function(option)
{
this.options = (option ? option : 0);
this.testme();
},
testme : function()
{
this.options++;
},
showme : function()
{
alert(this.options);
return this.options;
}
});
var theClass = new myClass(200);
theClass.showme();
//will alert 201 and return 201
这很酷,所有 - 但类继承呢?这是OOP中的一件大事 - 可以说我们有一个单独的类,它是一个myClass
的子类。对于要在子类中重写任何方法,你可以通过的第一变量$super
,这将指向同一个名字的父母的方法 - 类似于范围分辨率
var myChildClass = Class.create(myClass,
{
initialize : function($super,option)
{
$super(option);
// the child class needs option's default value at 150 or whatever is
// passed so run the parent initialize first and then redefine the
// option property
this.option = (option ? option : 150);
// you can still run methods in the parent that are not overridden in
// the child
this.testme();
}
});
var child = new myChildClass();
child.showme();
//will alert() 151 and return 151
我希望这是有帮助您。
这里是从我的github一些更复杂的现实世界的例子
https://github.com/jwestbrook/Prototype.Growler
我们可以创建类只用纯HTML文件的prototype.js或我们需要帮助任何其他工具? – 2013-03-25 08:43:23
PrototypeJS核心库中提供'Class.create()',您不需要任何其他JavaScript库来实现该方法。 – 2013-03-25 16:01:26
我们必须在同一个html页面或另一个html页面中写入子类函数? – 2013-03-26 10:17:45