JavaScript Tutorial 04 #Function#

var strict = (function() {
    return !this;
}());
//
function getPropertyNames(o, /* optional */ a) {
    if (a === undefined) a = []; /* a = a || [] */
    for(var property in o) {
        a.push(property);
    }
    return a;
}
/* callee 当前正在执行的函数, caller 当前正在执行的函数的函数 */
//
var scope = "global scope";
function checkscope() {
    var scope = "local scope";
    function f() {
        return scope;
    }
    return f;
}
checkscope()();
//
function costfuncs() {
    var funcs = [];
    for(var i = 0; i < 10; i++) {
        funcs[i] = function() {
            return i;
        }
    }
    return funcs;
}
var funcs = costfuncs();
funcs[5](); //return 10? shared var i

/* apply call */

/* bind */
function f(y) {
    return this.x + y;
}
var o = {x: 1};
var g = f.bind(o);
g(2); // => 3

/* */
function isFunction(x) {
    return Object.prototype.toString.call(x) === "[object Function]";
}

function not(f) {
    return function() {
        var result = f.apply(this,arguments);
        return !result;
    };
}

function memorize(f) {
    var cache = {};
    return function() {
        var key = arguments.length + "," + Array.prototype.join.call(arguments,",");
        console.log(key);
        if(key in cache) {
            return cache[key];
        } else {
            return cache[key] = f.apply(this,arguments);
        }
    };
}
function gcd(a,b) {
    var t;
    if(a<b) {
        t=b;
        b=a;
        a=t;
    }
    while(b!=0) {
        t=b;
        b=a%b;
        a=t;
    }
    return a;
}
var gcddemo = memorize(gcd);
gcddemo(85,187);

原文地址:https://www.cnblogs.com/lambdatea/p/3377892.html