你最喜欢的Mootools/Prototype原生对象原型是什么?

tj1*_*111 9 javascript mootools prototypejs

我们的Mootoolers和Prototypers(本网站上很少有人)通常带有一个方便的工具箱,我们创建(或借用)我们在本机javascript对象上实现的功能,使我们的生活更轻松.我希望得到一个非常有用的原型函数列表,但只能在本机对象上实现(即String.implement({...在mootools中).

那么,你最喜欢的是什么?


PS:我包括mootools和原型,因为为一个库编写的函数很容易移植到另一个库.

PPS:我知道/反对原型javascript对象原型的论据,我宁愿在这里避免讨论.

tj1*_*111 1

以下是我最喜欢的一些 mootools。

字符串函数

String.implement({

    //easy way to test if a string contains characters (input.value.isEmpty())
    isEmpty : function() {
        return (!this.test(/\w+/));
    },

    //add ellipses if string length > len
    ellipse : function(len) {
        return (this.length > len) ? this.substr(0, len) + "..." : this;
    },

    //finds all indexOf occurrences
    indexesOf : function(val) {
        var from = 0;
        var indexes = [];
        while (0 <= from && from < this.length) {
            var idx = this.indexOf(val, from);
            if (idx >= 0) {
                indexes.push(idx);
            } else {
                break;
            }
            from = idx+1;
        }
        return indexes;
    }
});
Run Code Online (Sandbox Code Playgroud)

数组函数

Array.implement({

    //compare two arrays to see if they are identical
    compare : function(arr, strict) {
        strict = strict || false;
        if (this.length != arr.length)          return false;

        for (var i = 0; i < this.length; i++) {
            if ($type(this[i]) == "array") {
                if (!this[i].compare(arr[i]))   return false;
            }
            if (strict) {
                if (this[i] !== arr[i])     return false;
            } else {
                if (this[i] != arr[i])      return false;
            }
        }
        return true;
    },

    //remove non-unique array values
    unique : function() {
        for(var i = 0; i< this.length; i++) {
            var keys = this.indexesOf(this[i]);
            while (keys.length > 1) {
                this.splice(keys.pop(), 1);
            }
        }
        return this;
    },

    //same as array.unshift, except returns array instead of count
    //good for using inline... array.lpush('value').doSomethingElse()
    lpush : function() {
        for (var i = arguments.length -1 ; i >= 0; i--){
            this.unshift(arguments[i]);
        }
        return this;
    },

    //get all indexes of an item in an array
    indexesOf : function(item) {
        var ret = [];
        for (var i = 0; i < this.length; i++) {
            if (this[i] == item)    ret.push(i);
        }
        return ret;
    }
});
Run Code Online (Sandbox Code Playgroud)