`
k1280000
  • 浏览: 203747 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Js code : utility

 
阅读更多
/**
 * defineClass( ) -- a utility function for defining JavaScript classes.
 *
 * This function expects a single object as its only argument.  It defines
 * a new JavaScript class based on the data in that object and returns the
 * constructor function of the new class.  This function handles the repetitive
 * tasks of defining classes: setting up the prototype object for correct
 * inheritance, copying methods from other types, and so on.
 *
 * The object passed as an argument should have some or all of the
 * following properties:
 *
 *      name: The name of the class being defined.
 *            If specified, this value will be stored in the classname
 *            property of the prototype object.
 *
 *    extend: The constructor of the class to be extended. If omitted,
 *            the Object( ) constructor will be used. This value will
 *            be stored in the superclass property of the prototype object.
 *
 * construct: The constructor function for the class. If omitted, a new
 *            empty function will be used. This value becomes the return
 *            value of the function, and is also stored in the constructor
 *            property of the prototype object.
 *
 *   methods: An object that specifies the instance methods (and other shared
 *            properties) for the class. The properties of this object are
 *            copied into the prototype object of the class. If omitted,
 *            an empty object is used instead. Properties named
 *            "classname", "superclass", and "constructor" are reserved
 *            and should not be used in this object.
 *
 *   statics: An object that specifies the static methods (and other static
 *            properties) for the class. The properties of this object become
 *            properties of the constructor function. If omitted, an empty
 *            object is used instead.
 *
 *   borrows: A constructor function or array of constructor functions.
 *            The instance methods of each of the specified classes are copied
 *            into the prototype object of this new class so that the
 *            new class borrows the methods of each specified class.
 *            Constructors are processed in the order they are specified,
 *            so the methods of a class listed at the end of the array may
 *            overwrite the methods of those specified earlier. Note that
 *            borrowed methods are stored in the prototype object before
 *            the properties of the methods object above. Therefore,
 *            methods specified in the methods object can overwrite borrowed
 *            methods. If this property is not specified, no methods are
 *            borrowed.
 *
 *  provides: A constructor function or array of constructor functions.
 *            After the prototype object is fully initialized, this function
 *            verifies that the prototype includes methods whose names and
 *            number of arguments match the instance methods defined by each
 *            of these classes. No methods are copied; this is simply an
 *            assertion that this class "provides" the functionality of the
 *            specified classes. If the assertion fails, this method will
 *            throw an exception. If no exception is thrown, any
 *            instance of the new class can also be considered (using "duck
 *            typing") to be an instance of these other types.  If this
 *            property is not specified, no such verification is performed.
 **/
function defineClass(data) {
    // Extract the fields we'll use from the argument object.
    // Set up default values.
    var classname = data.name;
    var superclass = data.extend || Object;
    var constructor = data.construct || function( ) {};
    var methods = data.methods || {};
    var statics = data.statics || {};
    var borrows;
    var provides;

    // Borrows may be a single constructor or an array of them.
    if (!data.borrows) borrows = [];
    else if (data.borrows instanceof Array) borrows = data.borrows;
    else borrows = [ data.borrows ];

    // Ditto for the provides property.
    if (!data.provides) provides = [];
    else if (data.provides instanceof Array) provides = data.provides;
    else provides = [ data.provides ];

    // Create the object that will become the prototype for our class.
    var proto = new superclass( );

    // Delete any noninherited properties of this new prototype object.
    for(var p in proto)
        if (proto.hasOwnProperty(p)) delete proto[p];

    // Borrow methods from "mixin" classes by copying to our prototype.
    for(var i = 0; i < borrows.length; i++) {
        var c = data.borrows[i];
        borrows[i] = c;
        // Copy method properties from prototype of c to our prototype
        for(var p in c.prototype) {
            if (typeof c.prototype[p] != "function") continue;
            proto[p] = c.prototype[p];
        }
    }
    // Copy instance methods to the prototype object
    // This may overwrite methods of the mixin classes
    for(var p in methods) proto[p] = methods[p];

    // Set up the reserved "constructor", "superclass", and "classname"
    // properties of the prototype.
    proto.constructor = constructor;
    proto.superclass = superclass;
    // classname is set only if a name was actually specified.
    if (classname) proto.classname = classname;

    // Verify that our prototype provides all of the methods it is supposed to.
    for(var i = 0; i < provides.length; i++) {  // for each class
        var c = provides[i];
        for(var p in c.prototype) {   // for each property
            if (typeof c.prototype[p] != "function") continue;  // methods only
            if (p == "constructor" || p == "superclass") continue;
            // Check that we have a method with the same name and that
            // it has the same number of declared arguments.  If so, move on
            if (p in proto &&
                typeof proto[p] == "function" &&
                proto[p].length == c.prototype[p].length) continue;
            // Otherwise, throw an exception
            throw new Error("Class " + classname + " does not provide method "+
                            c.classname + "." + p);
        }
    }

    // Associate the prototype object with the constructor function
    constructor.prototype = proto;

    // Copy static properties to the constructor
    for(var p in statics) constructor[p] = data.statics[p];

    // Finally, return the constructor function
    return constructor;
}


 


Example 9-11 shows sample code that uses the defineClass( ) method.

Example 9-11. Using the defineClass( ) method
// A Comparable class with an abstract method
// so that we can define classes that "provide" Comparable.
var Comparable = defineClass({
    name: "Comparable",
    methods: { compareTo: function(that) { throw "abstract"; } }
});

// A mixin class with a usefully generic equals( ) method for borrowing
var GenericEquals = defineClass({
    name: "GenericEquals",
    methods: {
        equals: function(that) {
            if (this == that) return true;
            var propsInThat = 0;
            for(var name in that) {
                propsInThat++;
                if (this[name] !== that[name]) return false;
            }

            // Now make sure that this object doesn't have additional props
            var propsInThis = 0;
            for(name in this) propsInThis++;

            // If this has additional properties, then they are not equal
            if (propsInThis != propsInThat) return false;

            // The two objects appear to be equal.
            return true;
        }
    }
});
// A very simple Rectangle class that provides Comparable
var Rectangle = defineClass({
    name: "Rectangle",
    construct: function(w,h) { this.width = w; this.height = h; },
    methods: {
        area: function( ) { return this.width * this.height; },
        compareTo: function(that) { return this.area( ) - that.area( ); }
    },
    provides: Comparable
});
// A subclass of Rectangle that chains to its superclass constructor,
// inherits methods from its superclass, defines an instance method and
// a static method of its own, and borrows an equals( ) method.
var PositionedRectangle = defineClass({
    name: "PositionedRectangle",
    extend: Rectangle,
    construct: function(x,y,w,h) {
        this.superclass(w,h);  // chain to superclass
        this.x = x;
        this.y = y;
    },
    methods: {
        isInside: function(x,y) {
            return x > this.x && x < this.x+this.width &&
                y > this.y && y < this.y+this.height;
        }
    },
    statics: {
        comparator: function(a,b) { return a.compareTo(b); }
    },
    borrows: [GenericEquals]
});

 

 
分享到:
评论

相关推荐

    Fullstack Vue: The Complete Guide to Vue.js

    Build bullet-proof apps with Testing: Use Vue’s official test utility library, vue-test-utils, to create meaningful tests for a daily weather app that interacts with a third party API.

    gcal-utility:从 code.google.compgcal-utility 自动导出

    【gcal-utility:自动化谷歌日历导出工具】 gcal-utility 是一款基于 JavaScript 开发的工具,其主要功能是从 Google 日历(Google Calendar)服务中自动导出日程信息。这款工具最初托管在 code.google....

    which-key-code:哪些键映射到什么键盘代码?

    "which-key-code"这个项目可能是一个工具或库,它帮助开发者识别和处理键盘上的不同按键与它们对应的键码。键码(Key Codes)是计算机编程中用来表示特定键盘按键的数值,这些值通常用于监听和响应用户的键盘输入。 ...

    JavaScript Code Improver

    JavaScript Code Improver is an easy-to-use utility that makes the JavaScript code in your Web pages well-structured and easily comprehensible thus saving the time you spend on editing, debugging ...

    code-in-js:JavaScript代码示例和实用程序脚本

    "code-in-js"项目显然是一系列JavaScript代码示例和实用工具脚本的集合,旨在帮助开发者理解和学习JavaScript的核心概念以及实际应用。 在"code-in-js-master"这个压缩包中,我们可以期待找到各种不同类型的...

    code-utility:美化,缩小,格式化或转换代码的在线工具

    实用程序这是一个开源项目,提供在线工具以美化,缩小和转换您的代码。 任何错误修复,增强功能,贡献都值得欢迎。 Ruby 2.6.5 Rails 6.0.3.2 PostgreSQL 10 Nginx 1.xx设置开发环境安装Nginx 安装Docker和Docker ...

    google-maps-utility-library-v3-只读:http:google-maps-utility-library-v3.googlecode.comsvn的git克隆

    一些库具有指向googlecode的CDN的硬编码网址。 Google的CDN关闭后,此网址已更改为 。 但是,示例文件和某些编译文件不会更新。 请考虑使用自托管文件或至少手动设置网址。 检查库源以获取配置选项。 // Example ...

    google-maps-utility-library-v3:从 code.google.compgoogle-maps-utility-library-v3 自动导出

    使用google-maps-utility-library-v3,开发者可以通过引入相应的JavaScript文件,然后在代码中调用对应的类和方法,实现对谷歌地图API的扩展功能。同时,由于这些模块是开源的,开发者也可以根据需要对其进行修改和...

    ajaxpro将js是合并后(仅12.3k)再压缩的文件及使用方法,现正在正常使用。

    把regjs.cs放到App_Code文件夹, ajax.js放到js文件夹。此js是合并后再压缩,现正在正常使用中的。 用:regjs.RegAjax(Header, typeof(Default)); 代替:protected void Page_Load(object sender, EventArgs e)中...

    utility_front_knowledege:总结项目中遇到的实用前端知识点

    "utility_front_knowledege"这个压缩包文件很可能包含了各种前端开发中常用的技术、工具和最佳实践。虽然具体的文件内容无法直接查看,但我们可以根据常见的前端知识点进行详细讲解。 1. HTML与CSS基础: - 响应式...

    jQuery.in.Action.3rd.Edition.161729207

    Chapter 9 Beyond the DOM with jQuery utility functions Chapter 10 Talk to the server with Ajax Chapter 11 Demo: an Ajax-powered contact form Part 3 Advanced topics Chapter 12 When jQuery is not ...

    Beyond.jQuery.1484222342

    Beyond jQuery gives you the confidence to abandon your jQuery crutches and walk freely with the power of the "web API" and ...Chapter 12: Common JavaScript Utility Functions Chapter 13: Going Forward

    C#基类库大全

    JavaScript|Jquery相关 1.jQuery.cookie帮助类 访问系统相关 1.C#计算机信息类ComputerInfo 2.Api_Win32_Mac类工具包 3.在c#程序中放音乐的帮助类 GDI+相关,图像相关 1.生成缩略图的类文件SmallImage C#基础类库...

    gmaps-utility-gis

    gmaps-utility-gis 是一个基于JavaScript的开源库,最初从Google Code SVN导入,由@jtroe在2015年4月2日迁移至当前的存储库。这个项目的重点在于提供一系列与谷歌地图API集成的实用工具,帮助开发者更高效地构建地理...

    ajax in prpc

    &lt;script type="text/javascript" src="/path/to/dojo/dojo.js"&gt; ``` 3. **Define What Packages You Are Using:** Similar to Java's "import" statement, this section specifies every package that you are ...

    vscode-wpilib:Visual Studio Code WPILib扩展

    建立依赖关系节点JS-已在节点8上进行了测试。 Java-经过Java 11测试VS Code-用于开发/调试。 TS棉绒扩展Chrome调试扩展程序为了调试扩展,您将需要扩展的依赖关系。 Microsoft C ++扩展和Java扩展包。设置依赖关系...

    blog.extending-tailwind-css-screen-height-utility:“扩展Tailwind CSS屏幕高度实用程序”中使用的源代码-css source code

    什么? 演示扩展Tailwind CSS高度实用程序。 请参考tailwind.config.js 怎么跑 这是通过create-react-app引导的。 因此,安装NPM软件包并启动它。 yarn优先。 $ yarn $ yarn start

    Java SE 8 for the Really Impatient

    Coverage of using lambda expressions (closures) to write computation “snippets” that can be passed to utility functions The brand-new streams API that makes Java collections far more flexible and ...

    缝纫:业务场景中的实用程序库

    Javascript实用程序库,适用于业务场景。 没有依赖关系。 快速开始 使用npm: $ npm i sewing 在TypeScript / ESM中: import sewing from 'sewing' import isEmpty from 'sewing/dist/isEmpty' 在Node.js中: ...

    Manning jQuery in Action.pdf

    - **The Document Ready Handler**: The `$(document).ready()` function ensures that the DOM is fully loaded before running any JavaScript code, preventing errors related to elements not being ready. ...

Global site tag (gtag.js) - Google Analytics