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);
};
}
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;
})();
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?
I prefer to declare it in the constructor because the HTML code is a bit nicer.
EDIT: 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.)
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.