【问题标题】:How to create a class using prototype.js如何使用prototype.js 创建一个类
【发布时间】:2013-03-09 02:57:49
【问题描述】:

谁能展示一个使用prototype.js创建类的例子以及它是如何工作的。除了官方网站之外,谁能提供关于prototype.js的好例子和教程?

【问题讨论】:

    标签: javascript oop prototypejs


    【解决方案1】:

    创建 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

    https://github.com/jwestbrook/Prototype.Watermark

    https://github.com/jwestbrook/bootstrap-prototype

    【讨论】:

    • 我们可以只用prototype.js在纯html文件中创建类还是需要任何其他工具的帮助?
    • Class.create() 在 PrototypeJS 核心库中可用,您不需要任何其他 javascript 库来实现该方法。
    • 我们必须在哪里编写子类函数?在同一个 html 页面中还是在另一个页面中?
    • 你可以在同一个文件中创建子类,只要新的子类javascript在父类之下,或者只要父类存在,子类就可以继承它。
    猜你喜欢
    • 1970-01-01
    • 2016-01-21
    • 2016-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-26
    • 1970-01-01
    相关资源
    最近更新 更多