事件处理函数不适用于“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;
});

首先你需要创建一个UnShownclass的对象然后你就可以访问他们的属性。

编辑 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就是Older way to register event listeners

在AngularJS中,使用Angular's jqLite添加事件侦听器。

var windowElem = angular.element($window);

windowElem.on('scroll', function scrollListener (event) {
    console.log(event);
};

务必将 $window 添加到工厂函数的可注入列表中。