Skip to content

useContext 极简代码实现 #32

@leno23

Description

@leno23
/**start context demo */
let contextMap = {}; // 上下文map
let contextId = 0; // 当前上下文id

const useContext = () => contextMap[contextId]

function run(cb) {
    contextId++; // 创建新的上下文id
    contextMap[contextId] = contextMap[contextId] || {}; // 创建新的上下文
    cb();
}

const origin = setTimeout;
setTimeout = (cb, delay) => {    
    const id = contextId; // 闭包保存当前上下文id
    return origin(() => {
        contextId = id;
        cb();
    }, delay);
};
/**end context demo */

function foo(id, delay) {
    const ctx = useContext();
    ctx.id = id;
    setTimeout(bar, delay); // 记录当前的contextId
}

function bar() {
    const ctx = useContext();
    console.log(ctx.id);
}

// Test
run(() => foo(1, 700));
run(() => foo(2, 1000));
run(() => foo(3, 1500));

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions