Typescript淘汰赛保留“此"的最佳方法? [英] Typescript Knockout best way to retain 'this'?
问题描述
这是一个额外的问题 TypeScript和Knockout绑定到"this"问题-lambda函数需要吗? 提出了两种在敲除函数中保留 this 的方法:
This is an extra question to this TypeScript and Knockout binding to 'this' issue - lambda function needed? where two methods of retaining this inside a Knockout function is proposed:
class viewmodelclass {
declaredinconstructor: (args) => void;
constructor(public someobjects: Array) {
this.declaredinconstructor=(args) =>{
}
}
declaredoutside(args) {
}
declaredoutsidecorrectly = (args) => {
console.log(this);
};
}
产生此Javascript:
Producing this Javascript:
var viewmodelclass = (function () {
var _this = this;
this.declaredoutsidecorrectly = function (args) {
console.log(_this);
};
function viewmodelclass(someobjects) {
this.someobjects = someobjects;
this.declaredinconstructor = function (args) {
};
}
viewmodelclass.prototype.declaredoutside = function (args) {
};
return viewmodelclass;
})();
如果要在函数内使用 this ,则需要以下HTML代码:
If you want to use this inside the functions, the following HTML code is needed:
<div data-bind="foreach: someobjects" >
<a href="#" data-bind="click: $parent.declaredinconstructor">link 1</a>
<a href="#" data-bind="click: $parent.declaredoutside.bind($parent)">link 2</a>
<a href="#" data-bind="click: $parent.declaredoutsidecorrectly">link 3</a>
</div>
(应该)都可以,但是哪个更正确/更快?
Both (should) work but which is the more correct/faster?
我更喜欢在构造函数中声明它,因为HTML代码更好一些.
I prefer to declare it in the constructor because the HTML code is a bit nicer.
多亏了Basarat的视频,我记得一个关于Typescript的视频-Typescript通过在生成的Javascript中声明_this来帮助您保留它-但仅在必要时! (如果我没有写console.log(this)_this不会由Typescript生成.)
Thanks to Basarat's video I remembered a video about Typescript - Typescript will help you retain this - by declaring _this in the produced Javascript - but only if necessary! (Had I not written console.log(this) _this would not be produced by Typescript.)
结论-如果正确声明外部实现,则不会泄漏到HTML上,因此,正如阿米塔布(Amitabh)指出的那样,正确的答案是选择最有效的模式:将函数附加到每个实例或原型上./p>
Conclusion - when declared correctly the outside implementation will not leak out to the HTML so the correct answer is, as Amitabh points out, to choose the pattern that is most efficient: Attaching the function to each instance or to the prototype.
推荐答案
绝对喜欢模式1.原因是在模式2中,类的基础实现泄漏到了html中,这在我的书中是很糟糕的.
Definitely prefer pattern 1. The reason is that in pattern 2 the underlying implementation of the classes is leaking into the html which is bad in my book.
这篇关于Typescript淘汰赛保留“此"的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!