关于在对象自身作用域内访问其内部数组的技术咨询
Fixing Access to Object Internal Array in Methods
Hey there! I see the issue you're running into—let's get this sorted out. The core problem here has to do with how arrow functions handle this and some scoping missteps in your timer logic. Let's break it down and fix your code step by step.
What's Going Wrong?
- Arrow functions don't work for object methods: When you use arrow functions like
changeImage: (image) => { ... }, thethisinside those functions doesn't point to yourimageObj—it inheritsthisfrom the outer scope (most likely the globalwindowhere). That's why trying to accessimgArrdirectly fails. - Global scoping for
imageCycle: Right nowimageCycleis treated as a global variable instead of a property tied to your object, which can lead to unexpected behavior later. - Resetting
counteron every interval tick: Yourcountervariable gets set to 0 every time the interval runs, so it'll never actually increment properly. - Redundant parameter in the inner interval function: You're passing
imageas a parameter to the inner arrow function, which overrides theimageparameter from the outerchangeImagemethod.
Fixed Code
let imageObj = { imgArr: [ 'dead_battery.jpg', 'evolution.jpg', 'funny_cat_pic.jpg', 'funny_paper_guys.jpg', 'happy_image', 'wood_garden.jpg' ], currentImg: 0, changeImage: function(image) { let counter = 0; // Keep counter outside the interval to preserve its value this.imageCycle = setInterval(() => { // Use this.imgArr to access the object's array, and dynamic length instead of hardcoding 6 let randomNum = Math.floor(Math.random() * this.imgArr.length); image.src = `/images/${this.imgArr[randomNum]}`; counter++; console.log('Times Ran: ', counter); }, 3000); }, stopImage: function(terminate) { if (terminate) { clearInterval(this.imageCycle); // Access the object's imageCycle property } console.log('INTERVAL STOPPED'); console.log(this.imgArr[3]); // Use this to access the internal array }, imageCycle: undefined }
Key Changes Explained
- Switched arrow functions to regular functions for methods: Using
function()ensuresthisinsidechangeImageandstopImagerefers directly toimageObj, so we can safely accessthis.imgArrandthis.imageCycle. - Moved
counteroutside the interval: Now it retains its value between timer ticks and increments correctly. - Used
this.imgArr.lengthinstead of hardcoding 6: Makes your code more maintainable—if you add or remove images later, you won't have to update this number. - Tied
imageCycleto the object: Usingthis.imageCyclekeeps the timer reference scoped to your object instead of cluttering the global scope. - Removed redundant
imageparameter: The inner interval function already has access to theimageparameter fromchangeImagevia closure, so we don't need to pass it again.
Now you should be able to access imgArr correctly within your object's methods!
内容的提问来源于stack exchange,提问作者JoekorSan
相关产品推荐
相关产品推荐

