本文介绍了如何测试javascript闭包中的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这似乎是不可能的(可能是),但我想进入更多的TDD,我继续打开一堵墙与闭包。说我有以下:

This seems impossible (and it might be), but I'm trying to get into more TDD and I keep hitting a wall with closures. Say I have the following:

 c>将根据函数的调用方式(如果使用该函数)而改变。

It might me worth noting that if you're taking functions out like this for testing purposes only, it may be preferable to comment out or otherwise remove the code to access these before publishing it on your website, so it can't be abused. Also, be aware that this will change depending on how a function is invoked, if you are using it.

function createSomething(init, aaa) {
    function privateMethod(param) {
        return init[param];  //assuming this is more complicated, how can you test it?
    }

    function getData() {
        return init.data;
    }

    function getValue(name) {
        if (name === "privateNode" || typeof name !== "string") {
            return "permissionDenied";
        }
        return privateMethod(name);
    }
    // ----------------------------------
    if(aaa) return privateMethod;
    // ----------------------------------
    return {
        getData : getData,
        getValue: getValue
    };
}

var something = createSomething({
    privateNode : "allmysecrets",
    id : "1234",
    data : {
        stuff : "32t97gfhw3hg4"
    }
}, 1); // passing extra arg to get method

console.log(
    something('id'),
    something('privateNode')
) // 1234 allmysecrets

这篇关于如何测试javascript闭包中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 06:26