简体   繁体   English

Javascript 在匿名 function 中获取父级的属性

[英]Javascript getting property of parent inside anonymous function

I have a function that calls different functions inside of itself.我有一个 function,它在其内部调用不同的函数。 I need the inner functions to access a property of the parent function.我需要内部函数来访问父 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内部运行的函数才能访问我在fn上设置的属性。 fn could look like this: fn可能如下所示:

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.在您的代码中,console.log 永远不会被调用。 Below, I make it get called, and I change this to fn :下面,我让它被调用,并将this更改为fn

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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