I have this object and want to access the variable scrolled var scrolled = 10;
from the init
function within the scrollDown
function.
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. 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? and Explanation from MDN
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.