简体   繁体   中英

Javascript getting property of parent inside anonymous function

I have a function that calls different functions inside of itself. I need the inner functions to access a property of the parent function. The code looks like this:

function runFuncWithExtraProperty(fn) {
    fn.insertedProperty = 'myProperty';
    fn();
}

I need the functions that run inside of fn to be able to access the property I set on fn . fn could look like this:

function fn() {
    () => {
        console.log(this.insertedProperty);
    };
}

Does anyone know how I would accomplish something like this so I can add extra properties that can be used by the inner functions? Thanks!

In your code, the console.log never gets called. Below, I make it get called, and I change this to fn :

 function fn() { (() => { console.log(fn.insertedProperty); })(); } function runFuncWithExtraProperty(fn) { fn.insertedProperty = 'myProperty'; fn(); } runFuncWithExtraProperty(fn);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM