class: захват и сохранение this
Это - работает:
var ClassWithId = (function() { function ClassWithId(id) { this.id = id; } return ClassWithId; }()); var ClassWithClosures = (function() { var me; function ClassWithClosures(id) { me = this; this.id = id; } ClassWithClosures.prototype.isMatch = function(num) { return (function(_num) { return !!me.id.id && _num % 2 === 0; })(num); }; return ClassWithClosures; }()); var arrayOfInt = [1, 2, 3, 4, 5, 6, 7, 8, 9]; var classWithClosure = new ClassWithClosures(new ClassWithId("blah")); var resultOfFilter = arrayOfInt.filter(classWithClosure.isMatch); for (var i = 0, l = resultOfFilter.length; i < l; i++) { if (window.console && console.log) { console.log(resultOfFilter[i]); } } Как заставить работать это: class ClassWithClosuresNewStyle { var me; !!! error "Uncaught SyntaxError: unexpected token: identifier" constructor(id) { this.id = id; } isMatch(num) { return(function(_num) { return !!me.id.id && _num %2 === 0; })(num); } } var arrayOfInt = [1, 2, 3, 4, 5, 6, 7, 8, 9]; var classWithClosureNewStyle = new ClassWithClosuresNewStyle(new ClassWithId("blah")); var resultOfFilter = arrayOfInt.filter(classWithClosureNewStyle.isMatch); for (var i = 0, l = resultOfFilter.length; i < l; i++) { if (window.console && console.log) { console.log(resultOfFilter[i]); } } ??? Ну... И... Первоисточник, така сказать, на TypeScript class ClassWithId { constructor(public id?: string) { } } class ClassWithClosures { constructor(public id?: ClassWithId) { } public isMatch(num: number): boolean { const tmpId = this.id; return ((_id: ClassWithId, _num: number) => { return !!_id.id && _num % 2 === 0; })(tmpId, num); } } let arrayOfInt = [1, 2, 3, 4, 5, 6, 7, 8, 9]; let classWithClosure = new ClassWithClosures(); let resultOfFilter = arrayOfInt.filter(classWithClosure.isMatch); for (let i = 0, l = resultOfFilter.length; i < l; i++) { if (window.console && console.log) { console.log(resultOfFilter[i]); } } ??? |
Всем спасибо - заборол:
class ClassWithClosuresNewStyle { constructor(id) { this.id = id; } isMatch = (num) => { return !!this.id.id && num %2 === 0; } } |
Часовой пояс GMT +3, время: 16:06. |