Angular 2. Http.订阅:"这个"指针

kor*_*ead 9 typescript angular

拿到:

http.request('js/app/config/config.json').subscribe(data => {
            this.url = data.json().url;
        });
Run Code Online (Sandbox Code Playgroud)

并以某种方式"这"指向订阅者.不知道为什么......因为我认为fat-arrow lambda会捕获父类的指针.

为什么这样?

bas*_*rat 8

根据截图:http://d.pr/i/iBa

在此输入图像描述

您正在this控制台中进行调试.请注意,this在控制台上将是实际的.当TypeScript为非ES6 JavaScript生成箭头函数时(它没有对箭头函数的本机支持)this映射到_this(和其他东西),这意味着您需要查看_this.

小费

在学习TypeScript时只需调试生成的JavaScript.这是TypeScript错误:https://github.com/Microsoft/TypeScript/issues/2859如果您有兴趣.


Ven*_*t.R 1

这是 ES6 箭头函数功能,可以避免为上下文创建更多变量。您可以\xe2\x80\x99t 覆盖箭头函数\xe2\x80\x99s“this”。

\n\n
http.request(\'js/app/config/config.json\').subscribe(function(data) {\n  this.url = data.json().url;\n});\n
Run Code Online (Sandbox Code Playgroud)\n\n

请参阅此文档:\n http://derickbailey.com/2015/09/28/do-es6-arrow-functions-really-solve-this-in-javascript/

\n