【发布时间】:2013-03-09 02:57:49
【问题描述】:
谁能展示一个使用prototype.js创建类的例子以及它是如何工作的。除了官方网站之外,谁能提供关于prototype.js的好例子和教程?
【问题讨论】:
标签: javascript oop prototypejs
谁能展示一个使用prototype.js创建类的例子以及它是如何工作的。除了官方网站之外,谁能提供关于prototype.js的好例子和教程?
【问题讨论】:
标签: javascript oop prototypejs
创建 PrototypeJS 类与使用普通 OOP 语言创建类非常相似。
首先为你的班级命名
var myClass = Class.create({ });
这将创建一个空类 - 现在用方法填充它,如果您放置一个方法 initialize PrototypeJS 将触发它作为构造函数
var myClass = Class.create(
{
initialize : function()
{
this.options = 0;
}
});
你可以在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
【讨论】:
Class.create() 在 PrototypeJS 核心库中可用,您不需要任何其他 javascript 库来实现该方法。