事件处理函数不适用于“this”关键字
Event handling function not working with `this` keyword
为什么我不能从事件处理程序中的this
关键字获取数据,如何修复?
twittyApp.factory('Unshown', function () {
function Unshown() {
this.allIsLoaded = false;
this.loading = false;
this.firstTime = true;
this.scrollMarker = 100;
this.loadedUnshownPages = 0;
this.timeLineHiader = $cookies.get("lastReadedTweetId");
}
window.onscroll = function () {
//why here this.scrollMarker is undefined?
};
return Unshown;
});
做这个改变
twittyApp.factory('Unshown', function() {
var fact = {};
function Unshown() {
this.allIsLoaded = false;
this.loading = false;
this.firstTime = true;
this.scrollMarker = 100;
this.loadedUnshownPages = 0;
this.timeLineHiader = $cookies.get("lastReadedTweetId");
}
var objUnShown = new Unshown();
window.onscroll = function() {
objUnShown.scrollMarker // aceess scrollmarker
};
fact.Unshown =objUnShown;
return fact.Unshown;
});
首先,您需要创建一个类的对象UnShown
然后您可以访问其属性。
编辑 2 :如果你想随时创建对象,你可以通过这种方式来完成。
twittyApp.factory('Unshown', function() {
var fact = {};
function Unshown() {
..
}
window.onscroll = function() {
objUnShown.scrollMarker // aceess scrollmarker
};
fact.Unshown =Unshown;
return fact;
});
/// in controller do this.
var objUnshown = new Unshown.Unshown()
通过在Unshown
函数中使用 this
关键字,可以设置该函数对象的属性。若要访问函数外部的这些属性,请在函数对象引用上使用属性访问器。
twittyApp.factory('Unshown', function () {
function Unshown() {
this.allIsLoaded = false;
this.loading = false;
this.firstTime = true;
this.scrollMarker = 100;
this.loadedUnshownPages = 0;
this.timeLineHiader = $cookies.get("lastReadedTweetId");
}
window.onscroll = function () {
//this.scrollMarker is undefined
//
//Use property accessor
console.log(Unshown.scrollMarker);
};
return Unshown;
});
在 AngularJS 中使用window.onscroll
使用 window.onscroll
是注册事件侦听器的旧方法。
在 AngularJS 中,事件侦听器是使用 Angular 的 jqLite 添加的。
var windowElem = angular.element($window);
windowElem.on('scroll', function scrollListener (event) {
console.log(event);
};
请务必将$window
添加到工厂功能的注射剂列表中。
相关文章:
- JavaScript 中的嵌套函数和 “this” 关键字
- Javascript 对象和 this 关键字
- 将“this”关键字发送到对象中
- 如何使用“this”关键字来调用a
- 组合类和事件监听器:`this`关键字
- 将this关键字与selectedIndex一起使用的优势
- 在forEach中调用类函数:Javascript如何处理“this”关键字
- 使用“this”关键字响应类行为
- Javascript 'this' 关键字 在嵌套函数中
- 事件处理函数不适用于“this”关键字
- (无效)如何在 JSON 中使用“this”关键字
- JavaScript Promise 和 this 关键字
- 如何在 html 中使用“this”关键字在对象上调用方法
- Javascript中“this”关键字的目的是什么?
- 处理 jQuery 事件时在 JavaScript 类中覆盖的 'this' 关键字
- PHP 相当于 JavaScript “this” 关键字,特别是在对象中
- 嵌套函数中“this”关键字的范围
- 在我的命名空间JavaScript中使用this关键字
- JavaScript 中的 'this' 关键字
- Javascript [this] 关键字绑定与 new