我有这个对象,想要从var scrolled = 10;
函数中的init
函数访问滚动scrollDown
的变量。
我无法访问变量。我怎样才能做到这一点?
// 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();
答案 0 :(得分:1)
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();
或
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();
答案 1 :(得分:0)
根据您的问题,您应该使用this.scrolled
而不是var。一个例子是
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();
为了满足您的好奇心,您应该查看此链接How does the “this” keyword work?和Explanation from MDN