utils.js

自分用のユーティリティ・ライブラリ。
 

var Utils = (function () {
    var d = document;
    
    _print = function (str) {
      d.writeln(str + "  ");
    }
    
    _getById = function (str) {
      return d.getElementById(str);
    }
    
    _getByClass = function (str) {
      return d.getElementsByClassName(str);
    }
    
    _getByTag = function (str) {
      return d.getElementsByTagName(str);
    }

    return {
        getById: _getById,
        getByClass: _getByClass,
        getByTag: _getByTag
    };
}());


//オブジェクト名を String で返す
Object.prototype.class = function () {
    var a;
    if (this instanceof HTMLDocument) a = "HTMLDocument";
    else if (this instanceof HTMLCollection) a = "HTMLCollection";
    else if (this instanceof Node) a = "Node";
    else if (this instanceof String) a = "String";
    else if (this instanceof Array) a = "Array";
    else if (this instanceof Date) a = "Date";
    else if (this instanceof RegExp) a = "RegExp";
    else if (this instanceof Boolean) a = "Boolean";
    else if (this instanceof Number) a = "Number";
    else if (typeof(this) === 'function') a = "function";
    else if (this instanceof Object) a = "Object";
    else a = "Other";
    return a;
}
/* 判定できないもの: Global */


//Ruby の to_s みたいなもの
Object.prototype.to_s = function () {
    if (typeof(this) === "function") return "function";
    return this.toString();
}

String.prototype.to_s = function () {
    return '"' + this + '"';
}

Array.prototype.to_s = function () {
    var a = "[";
    a += this.map(function(i) {
        return i.to_s();
    }).join(", ");
    a += "]";
    return a;
}