您的位置:首页 > Web前端 > JavaScript

js创建对象 对象如何继承 及一些工具函数

2011-11-24 16:44 423 查看
function Rectangle(w, h) {
this.width = w;
this.height = h;
}
Rectangle.prototype.area = function () { return this.width * this.height; }; //类的实例方法 建议为原型对象定义方法而不是放在构造函数定义方法
Rectangle.prototype.toString = function () { return "[" + this.width + "," + this.height + "]"; };//这样性能更好,所有的对象共享同一个方法,对象继承之对象原型

function PositionRectangle(x, y, w, h) {
// Rectangle.apply(this, [w, h]); //调用父类的构造函数
this.superclass(w, h); //通过给原型追加属性 调用父类的构造函数
this.x = x;
this.y = y;
}
PositionRectangle.prototype = new Rectangle();//子类的原型为超类的实例
PositionRectangle.prototype.superclass = Rectangle;//为原型添加属性方便调用父类构造函数
PositionRectangle.prototype.constructor = PositionRectangle; //设置原型的constructor

delete PositionRectangle.prototype.width;//删除超类构造函数在原型中创建的属性
delete PositionRectangle.prototype.height; //删除超类构造函数在原型中创建的属性

PositionRectangle.prototype.contains = function (x, y) {
return (this.x < x && x < this.x + this.width, this.y < y && y < this.y + this.height);
}
PositionRectangle.prototype.toString = function () {
return "(" + this.x + "," + this.y + ")" + this.superclass.prototype.toString.apply(this);//调用父类的同名方法
};

function getPropertyName(/*object */o, /*option array*/r) {
var r = r || [];
for (var name in o) {
r.push(name);
}
return r;
}

function copyProperties(/*object from*/from, /*object to*/to) {
var to = to || {};
for (var p in from) {
to[p] = from[p];
}
return to;
}

function copyUndefinedProperties(/*object from*/from, /*object to*/to) {
for (var p in from) {
if (to[p] === undefined)
to[p] = from[p];
}
return to;
}

function filterArray(/*Array*/a, /*predicate*/predicate) {
var result = [];
for (var i = 0; i < a.length; i++) {
if (predicate(a[i])) {
result.push(a[i]);
}
}
return result;
}

function mapArray(/*Array*/a, /*function*/f) {
var r = [];
for (var i = 0; i < a.length; i++) {
r[i] = f(a[i]);
}
return r;
}
String.prototype.trim = function () {
return this.replace(/(^\s*)|(\s*$)/g, "");
}
String.prototype.ltrim = function () {
return this.replace(/(^\s*)/g, "");
}
String.prototype.rtrim = function () {
return this.replace(/(\s*$)/g, "");
}

//从一个类借用方法到另一个类
function borrowMethods(borrowfrom, addTo) {
var from = borrowfrom.prototype;
var to = addTo.prototype;
for (var name in from) {
if (typeof from[name] != "function") continue;
to[name] = from[name];
}
}
//通用字符串方法
function GenericToString() { };
GenericToString.prototype.toString = function () {
var props = [];
for (var name in this) {
if (!this.hasOwnProperty(name)) continue;
var value = this[name];
var s = name + ":";
switch (typeof value) {
case "function":
s += "function";
break;
case "object":
if (value instanceof Array) {
s += "Array";
}
else if (value instanceof Date) {
s += "Date";
}
else {
s += "object";
}
break;
default:
s += new String(value);
break;
}
props.push(s);
}
return "{" + props.join(", ") + "}";
};
//简单对象相等
function GenericEquals() { };
GenericEquals.prototype.equals = function (that) {
if (this == that) return true;
var propInThat = 0;
for (var name in that) {
propInThat++;
if (this[name] !== that[name])
return false;
}
var propInThis = 0;
for (var name in this) {
propInThis++;
if (this[name] !== that[name])
return false;
}
if (propInThat != propInThis) return false;
return true;
}
//扩展typeof测试
function getType(x) {
if (x == null) return "null";
var t = typeof x;
if (t != "object") return t;
var c = Object.prototype.toString.apply(x);
c = c.substring(8, c.length - 1);
if (c != "Object") return c;
if (x.constructor == Object) return c;
if ("classname" in x.constructor.prototype && typeof x.constructor.prototype.classname == "string")
return x.constructor.prototype.classname;
var name = new String(x.constructor);
var reg = /function([^\(]+)\(/;
var result = name.match(reg);
if (result != null) {
result = result[1];
result = result.replace(/(^\s*)|(\s*$)/g, "");
return result;
}

return "<unknown type>";
}
//测试类似数组的对象
function isArrayLike(x) {
if (x instanceof Array) return true;
if (!("length" in x)) return false;
if (typeof x.length != "number") return false;
if (x.length < 0) return false;
if (x.length > 0) {
if (!(x.length - 1 in x)) return false;
}
return true;
}
//定义类的一个工具函数
function defineClass(data) {
var classname = data.name;
var superclass = data.extend || Object;
var constructor = data.constructor || function () { };
var methods = data.methods || {};
var statics = data.statics || {};
var borrows, provides;
if (!data.borrows) {
borrows = [];
}
else if (data.borrows instanceof Array) {
borrows = data.borrows;
}
else {
borrows = [data.borrows];
}

if (!data.provides) {
provides = [];
}
else if (data.provides instanceof Array) {
provides = data.provides;
}
else {
provides = [data.provides];
}

var proto = new superclass();
for (var p in proto) {
if (proto.hasOwnProperty(p))
delete proto[p];
}

for (var i = 0; i < borrows.length; i++) {
var c = borrows[i];
for (var p in c.prototype) {
if (typeof c.prototype[p] != "function") continue;
proto[p] = c.prototype[p];
}
}

for (var p in methods) {
proto[p] = methods[p];
}

proto.constructor = constructor;
proto.superclass = superclass;
if (classname) proto.classname = classname;

for (var i = 0; i < provides.length; i++) {
var c = provides[i];
for (var p in c.prototype) {
if (typeof c.prototype[p] != "function") continue;
if (p == "constructor" || p == "superclass") continue;
if (p in proto && typeof proto[p] == "function" && proto[p].length == c.prototype[p].length) continue;
throw new Error("Class "+classname+" does not provide method "+c.classname+"."+p);
}
}
constructor.prototype = proto;
for (var p in statics) {
constructor[p] = statics[p];
}
return constructor;
}
//用类名和标记明选择html元素
function getElements(classname, tagname, root) {
    if (!root) root = document;
    if (typeof root == "string" || root instanceof String) {
        root = document.getElementById(root);
    }
    if (!tagname) tagname = "*";
    var all = root.getElementsByTagName(tagname);
    if (!classname) return all;
    var elements = new Array();
    for (var i = 0; i < all.length; i++) {
        var element = all[i];
        if (isMember(element, classname))
            elements.push(element);
    }
    return elements;
    function isMember(element, classname) {
        if (!classname) return false;
        var classes = element.className;
          return classes.search("\\b" + classname + "\\b") != -1;
    }
}
//翻转元素节点
function reverse(n) {
    if (n.constructor == String)
        n = document.getElementById(n);
    var f = document.createDocumentFragment();
    while (n.lastChild) f.appendChild(n.lastChild);
    n.appendChild(f);
}
// 记录对象的属性
function log(element, o) {
    if (element.constructor == String) {
        element = document.getElementById(element);
    }
    var caption = document.createTextNode("log object property and funcyion");
    element.appendChild(caption);
    var tb = makeTable(o, 0);
    element.appendChild(tb);
    function makeTable(object, level) {
        var table = document.createElement("table");
        table.border = 1;
        var tbody = document.createElement("tbody");
        table.appendChild(tbody);
        var header = document.createElement("tr");
        tbody.appendChild(header);
        var headerName = document.createElement("th");
        var headerType = document.createElement("th");
        var headerValue = document.createElement("th");
        headerName.appendChild(document.createTextNode("Name"));
        headerType.appendChild(document.createTextNode("Type"));
        headerValue.appendChild(document.createTextNode("Value"));
        header.appendChild(headerName);
        header.appendChild(headerType);
        header.appendChild(headerValue);

        var names = new Array();
        for (var name in object) {
            names.push(name);
        }
        names.sort();

        for (var i = 0; i < names.length; i++) {
            var name, type, value;
            name = names[i];
            try {
                value = object[name];
                type = typeof value
            } catch (e) {
                value = "<unknown value>";
                type = "unknown";
            }

            var row = document.createElement("tr");
            row.vAlign = "top";
            var rowName = document.createElement("td");
            var rowType = document.createElement("td");
            var rowValue = document.createElement("td");
            rowName.appendChild(document.createTextNode(name));
            rowType.appendChild(document.createTextNode(type));
            if (type == "object")
                rowValue.appendChild(makeTable(value, level + 1));
            else
                rowValue.appendChild(document.createTextNode(value));
            row.appendChild(rowName);
            row.appendChild(rowType);
            row.appendChild(rowValue);
            tbody.appendChild(row);
        }
        return table;
    }
}
//操作className的工具函数
var CSSClass = {};
CSSClass.is = function (e, c) {
    if (e.constructor == String)
        e = document.getElementById(e);
    var classes = e.className;
    if (classes == c) return true;
    return classes.search("\\b" + c + "\\b") != -1;
};
CSSClass.add = function (e, c) {
    if (e.constructor == String)
        e = document.getElementById(e);
    if (CSSClass.is(e, c)) return;
    if (e.className) c = " " + c;
    e.className += c;
};
CSSClass.remove = function (e, c) {
    if (e.constructor == String)
        e = document.getElementById(e);
    if (!CSSClass.is(e, c)) return;
    e.className = e.className.replace(new RegExp("\\b" + c + "\\b\\s*", "g"), "");
};
    function text(e) {
            //获取元素文本内容
            var t = "";
            e = e.childNodes || e;
            for (var i = 0, count = e.length; i < count; i++) {
                t += e[i].nodeType != 1 ? e[i].nodeValue : text(e[i].childNodes);
            }
            return t;
        }
        function attr(elem, name, value) {
            //获取或设置元素属性值
            if (!name || name.constructor != String) return "";
            name = { "for": "htmlFor", "class": "className"}[name] || name;
            if (typeof value != "undefined") {
                elem[name] = value;
                if (elem.setAttribute) {
                    elem.setAttribute(value);
                }
            }
            return elem[name] || elem.getAttribute(name)||"";
        }
 function stopDefault(e) {
        //防止默认浏览器行为
        if (e && e.preventDefault) {
            e.preventDefault();
        }
        else {
            window.event.returnValue = false;
        }
        return false;
    }
    function stopBubble(e) {
        //阻止事件冒泡
        if (e && e.stopPropagation) {
            e.stopPropagation();
        }
        else {
            window.event.cancelBubble = true;
        }
    }
    //调用示例<a href="#"  onclick=" alert('ok'); stopBubble(event);">demo</a> 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: