class: захват и сохранение this
#40017121
Ссылка:
Ссылка на сообщение:
Ссылка с названием темы:
Ссылка на профиль пользователя:
|
|
|
Это - работает:
1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31.
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]);
}
}
Как заставить работать это:
1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22.
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
1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26.
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]);
}
}
???
_________________
"Helo, word!" - 17 errors 56 warnings
|
|