有用的工具函数

本文摘自《Javascript权威指南》8.7节Page146

对象工具函数

var obj = {}; // <=> new Object();
 
// Add 'prop1'
obj.prop1 = 1;
 
// Add 'prop2'
obj.prop2 = 2;
 
// Delete 'prop1'
delete obj.prop1;
 
// Change value of 'prop2'
obj.prop2 = 3;

//Return a array that holds the names of the enumerable prpperties of a function get properties of o
function getPropertyNames(/*objects*/ o ){
    var r = [] ;
    for (name in o )
    {
        r.push(name);
    }
    return r;
}

//Copy the enumerable properties of the object "from" to the object "to".
//If "to" is null, a new object is created . The function returns "to" or the newly created object.
function copyProperties(/*object*/ from ,/*object*/ to ){
    if( ! to ) { to={};    }
    for ( p in from ){
        to[p] = from[p] ;
        return to;
    }
}

//Copy the enumerable properties of the object "from" to the object "to".
//but only the ones that are not already defined by to.
function copyUndefinedProperties(/*object*/ from ,/*object*/ to ){
        for ( !p in from ){
        to[p] = from[p] ;
        return to;
}

//Pass each element of the array " a "  to the specified "predicate" function.
//Return an array that holds the element for which the predicate returned true
function filterArray(/*array*/ a, /*boolean function*/ predicate ){
    var results = [];
    var length = a.length; //In case ,predicate change the length
    for (var i=0 ; i < length ;  i++ )
    {
        var element = a[i];
        if( predicate(element)) results.push(element);
    }
    return results;
}

//Return the array of values that result when each of the elements of the array "a" are passed to the function "f"
function mapArray ( /*array*/ a, /*function*/ f ){
    var r = []; //to hold the result
    var length = a.length; //In case ,f change the length
    for (var i=0 ; i<length ; i++ )
    {
        r[i] = f (a[i]);
        return r;
    }
}
 
function bindMethod(/* object */ o , /* function */ f ) {
     return function() { return f.apply ( o , arguments) }
 }
原文地址:https://www.cnblogs.com/yingzi/p/2582976.html