meh*_*dvd 4 javascript visual-studio typescript visual-studio-2013 typescript1.4
考虑以下代码:
class Person{
firstname = ko.observable<string>();
lastname: ko.observable<string>();
fullname = ko.computed(()=>{
// Breakpoint here
return this.firstname() + ' ' + this.lastname();
});
Run Code Online (Sandbox Code Playgroud)
当我使用Visual Studio 2013进行调试时,如果我放置断点并查看this使用watch或immediate窗口的值,则表明该值window不是person实例.因此,它表明undefined了this.firstname.
检查转换的JavaScript代码我发现我应该检查值_this而不是this.
虽然代码运行没有错误,但是它浪费了我很多时间来理解this变量的真正价值是可用的_this.
问题我在使用类属性时导致这个误导值的错误this吗?或者它只是一个错误?或者也许是出于某种原因设计的?
Nyp*_*pan 10
由于"this"关键字在javascript中的工作原理,Typescript会为您创建"_this"别名.这是设计的,当你知道它是如何工作的时候很棒.
你的例子:
class Person {
firstname = ko.observable<string>();
lastname: ko.observable<string>();
fullname = ko.computed(
() => {
// Breakpoint here
return this.firstname() + ' ' + this.lastname();
});
}
Run Code Online (Sandbox Code Playgroud)
编译为:
var Person = (function () {
function Person() {
var _this = this;
this.firstname = ko.observable();
this.lastname = ();
this.fullname = ko.computed(function () {
// Breakpoint here
return _this.firstname() + ' ' + _this.lastname();
});
}
return Person;
})();
Run Code Online (Sandbox Code Playgroud)
这显示(如您所述)您的全名计算函数中的"this"已编译为"_this".您调试的问题是Visual Studio正在调试已编译的JavaScript.并且在函数内部的javascript"this"意味着其他东西,在这里阅读更多关于"this"的内容.
使用lambda函数时,Typescript会创建一个_this引用,即:
class foo {
something: string = "some string";
foo1 = () => { this.something }
foo2() { this.something }
}
Run Code Online (Sandbox Code Playgroud)
编译为:
var foo = (function () {
function foo() {
var _this = this;
this.something = "some string";
this.foo1 = function () { _this.something; };
}
foo.prototype.foo2 = function () { this.something; };
return foo;
})();
Run Code Online (Sandbox Code Playgroud)
如果使用正确,打字稿中的lambda函数解决了javascript中的"this"地狱.在大多数情况下,您不需要考虑何时使用lambda或函数,但在某些情况下,您可以这样做.有关lambda函数的更多信息,请参见此处.
解决这个问题的简单方法是在使用lambdas时检查_this,直到它被修复为止.有一个未解决的问题:https://typescript.codeplex.com/workitem/1655.
| 归档时间: |
|
| 查看次数: |
1101 次 |
| 最近记录: |