Context of js

function l() {
    console.log(item);
}

[1, 2, 3].forEach(item => {
    l();
});
The

code is like this. I want to execute the l function in the context of forEach. Item, will be printed in the l function, but this will report an error. How should I correctly let the l function execute and print 1pm / 2min 3

Mar.25,2021

function l(item) {
    console.log(item);
}

[1, 2, 3].forEach(item => {
    l(item);
});


you didn't pass the parameters in.


js uses lexical scope, which means that for any variable, the context of is the context in which the variable is defined , rather than the context in use .

item is a local variable of an anonymous function in forEach. The function l is defined outside the anonymous function and cannot access the internal variables of the function.

the implementation of your topic can be used in languages with dynamic scope. At present, most languages use lexical scope

.
function l(){
    console.log(this);
}

[1, 2, 3].forEach(item => {
    l.call(item);
});

the execution environment of, l () that does not exist is global and cannot be accessed to item, except by passing parameters (previously answered) or accessing the item of l () 's execution environment (global).

var item;
function l() {
    console.log(item);
}

[1, 2, 3].forEach(ele => {
    item=ele;
    l();
}

or, put the execution environment of l () into forEach, that is, define l () into forEach.

[1, 2, 3].forEach(item => {
    function l() {
        console.log(item);
    }
    l();
});

l () function passes parameters


babel-plugin-macros allows you to create your own syntax, such as babel-macro-cxt .

Menu