2017-10-17 48 views
0

如何在打字稿中从单独的嵌入式函数内击中某个函数?嵌套方法中的命中方法

我试图完成什么...在伪;

export class blah { 

    functionOne(result) { 
     // do stuff with the result of functionTwoChildMethod... 
    }; 

    const geocoder = new google.maps.Geocoder(); 

    geocoder.geocode (paramObj, function (res, stat) { 

     functionTwoChildMethod =() => { 
     this.functionOne(result); 
     }; 

    }; 
}; 

似乎做this.functionOne(result);没有达到类范围的母体火过functionOne什么的。那么我错过了什么?感谢您的任何方向这已经困扰了我的时间比我愿意分享:)

回答

0

this将是疯狂的,我知道,但尝试that;)

export class blah { 

    functionOne(result) { 
     // do stuff with the result of functionTwoChildMethod... 
    }; 

    const geocoder = new google.maps.Geocoder(); 
    var that = this; 
    geocoder.geocode (paramObj, function (res, stat) { 

     functionTwoChildMethod =() => { 
     that.functionOne(result); 
     }; 

    }; 
}; 

this您使用的是一个范围在哪里没有你需要的功能内,但通过将其分配给that你能给我们您需要的功能;) 这是所有变量的作用域

+0

HA!是的......那不是我会猜到的逻辑!非常感谢!如果我也可以upvote,但我会,但我的代表太低了,但你要么我的感谢! :) – LearningNewStuff

+0

别担心,我只是高兴地帮助:) –

0

So what am I missing

this

修复

使用箭头功能

export class blah { 

    functionOne(result) { 
     // do stuff with the result of functionTwoChildMethod... 
    }; 

    const geocoder = new google.maps.Geocoder(); 

    geocoder.geocode (paramObj, (res, stat) => { // Use arrow here 

     functionTwoChildMethod =() => { 
     this.functionOne(result); 
     }; 

    }; 
}; 

更多

https://basarat.gitbooks.io/typescript/docs/arrow-functions.html

+0

我得到的未捕获TypeError:_this.functionOne不是函数 错误,似乎仍然没有找到它? – LearningNewStuff

+0

@LearningNewStuff然后你有更多的错误。我已经用箭头更新了答案 – basarat

+0

对不起,没有运气,也许我的例子有点含糊,是否会影响functionTwo是一个来自const对象的匿名函数?请参阅我更新的问题示例以了解更多具体信息,我正尝试从新的Google实例匿名函数之外获取信息,以便将API结果报告给其他方法。 – LearningNewStuff