简体   繁体   English

如何访问另一个函数 jquery 中的变量

[英]How can I access variable inside another function jquery

I have this object and want to access the variable scrolled var scrolled = 10;我有这个对象,想访问变量 scrolled var scrolled = 10; from the init function within the scrollDown function.来自scrollDown函数中的init函数。

I am having trouble accessing the variable.我在访问变量时遇到问题。 How can I achieve this?我怎样才能做到这一点?

// Summary Screen Functions
var summary = {
    init: function() {

        var scrolled = 0;

        $('.page-summary-action a').on('click', summary.continueToSummary);
        $('.scroll-down').on('click', summary.scrollDown);
        $('.scroll-up').on('click', summary.scrollUp);
    },

    scrollDown: function(e) {
        e.preventDefault();
        scrolled = scrolled + 300;

        console.log('clicked');

        $(".data-cards").animate({
            scrollTop:  scrolled
        });
    },

    scrollUp: function(e) {
        e.preventDefault();
        console.log('clicked');

        $(".data-cards").animate({
            scrollTop: 15
        });
    }
};

summary.init();
var scrolled = 0; // Put the variable in an outer scope
var summary = {
    init: function() {
        // access "scrolled"
        scrolled = 0;
    },

    scrollDown: function(e) {
        // access "scrolled"
    },

    scrollUp: function(e) {
        // ...
    }
};

summary.init();

or或者

var summary = {
    scrolled: 0, // Make it a property of the "summary" object
    init: function() {
        // access "scrolled"
        summary.scrolled = 0;
    },

    scrollDown: function(e) {
        // access "scrolled"
    },

    scrollUp: function(e) {
        // ...
    }
};

summary.init();

Following your question, you should use this.scrolled instead of var.按照您的问题,您应该使用this.scrolled而不是 var。 An example would be一个例子是

 var summary = {
    init: function() {
        this.scrolled = 20;
    },

    scrollDown: function(e) {
        console.log(this.scrolled);
    },

    scrollUp: function(e) {
        console.log(this.scrolled);
    }
 };   
 summary.init();
 summary.scrollDown();

to satisfy your curiosity, you should look up this link How does the “this” keyword work?为了满足您的好奇心,您应该查看此链接“this”关键字如何工作? and Explanation from MDNMDN 的解释

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM