简体   繁体   English

Javascript / Typescript->访问函数的先前作用域

[英]Javascript/Typescript -> Access Previous scope of a function

Is it possible to access the previous scope of a function in Javascript? 是否可以在Javascript中访问函数的先前作用域? Or is it possible to automaticaly assign "this" to a parameter in typescript when calling a function? 还是可以在调用函数时自动将“ this”分配给打字稿中的参数? (so I have the previous scope) (所以我有以前的范围)

for example: (a Function defined in my class Queryable) 例如:(在我的类Queryable中定义的函数)

    Where(filter: (part: T) => boolean): Queryable<T> {
    var ast = acorn.parse("(" + filter.toString() + ")"); ...

and I use it from outside: 我从外面使用它:

var aa = new Queryable<ITest>();
var jj = "bb";
aa.Where(x => x.content == "aa" && x.bb.content == jj || x.form.Contains("Hallo"));

now inside my Where function, I need to get the value of "jj" 现在在我的Where函数中,我需要获取“ jj”的值

Mabey a little bit more Code helps: 也许更多的代码可能会帮助:

class Queryable<T> {

    Where(filter: (part: T) => boolean): IQueryable<T> {
        var ast = acorn.parse("(" + filter.toString() + ")");

        return null;
    }
}

interface String {
    Contains(par: String): boolean;
    StartsWith(par: String): boolean;
    EndsWith(par: String): boolean;
}

interface ITest {
     content: string;
     form: string;
     href: string;
     bb: ITest;
     cc: ITest[];
}

function test() {
     var aa = new Queryable<ITest>();
     var jj = "bb";
     aa.Where(x => x.content == "aa" && x.bb.content == jj || x.form.Contains("Hallo"));
 }

 test();

And inside the "Where" I need to access the Variables wich were used in the function in his parameter 在“ Where”中,我需要访问他的参数中使用的变量

I do not think its possible to access 'previous' scope except for the case when its global scope (see more here ). 我不认为它可以访问“之前的”范围,除了当其全球范围内(看更多的情况下在这里 )。 And even if it where possible and you could get reference to 'this' it will not allow you to access variables. 即使可能,并且您可以引用“ this”,它也不允许您访问变量。

I would recommend to rework your approach and use instead of variables - objects of classes with properties designed to hold all required info. 我建议重新设计您的方法,并使用变量而不是变量-具有旨在容纳所有必需信息的属性的类的对象。 Then you will be able to pass instances of such parent object along with function calls and access its properties as needed. 然后,您将能够将此类父对象的实例与函数调用一起传递,并根据需要访问其属性。

Roughly like this: 大致像这样:

class Queryable<T> 
{
    public Where(parent: any, filter: (part: T) => boolean): IQueryable<T> 
    {
        var jj = parent.jj;
        var ast = acorn.parse("(" + filter.toString() + ")");
        return null;
    }
}

class Test 
{
    public jj;

    public Run()
    {
        this.jj = "bb";
        let aa = new Queryable<ITest>();
        aa.Where(this, x => x.content == "aa" && x.bb.content == this.jj || x.form.Contains("Hallo"));
    }
}

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

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