If you think a bug might affect users in the 57 release, please set the correct tracking and status flags for Release Management.

javascript: "this" loses context within forEach when used in a class

VERIFIED INVALID

Status

()

Core
JavaScript Engine
VERIFIED INVALID
10 years ago
8 years ago

People

(Reporter: Jason Hutchinson, Unassigned)

Tracking

Firefox Tracking Flags

(Not tracked)

Details

Attachments

(1 attachment)

(Reporter)

Description

10 years ago
User-Agent:       Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1.11) Gecko/20071204 Ubuntu/7.10 (gutsy) Firefox/2.0.0.11
Build Identifier: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1.11) Gecko/20071204 Ubuntu/7.10 (gutsy) Firefox/2.0.0.11

When a class is defined which uses forEach in one of its methods and you try to use the "this" keyword within that forEach function "this" refers to the window object, whereas the instance of the class is expected.

Reproducible: Always

Steps to Reproduce:
1. Create a class that has an array property (i.e. put this.aray=[]) in the constructor.
2. Add another property to the class, (e.g. this.myString="My String")
2. Create a method that loops through that array using forEach
3. Try to access the myString property via this.myString while inside of the function passed to forEach.
Actual Results:  
this.myString is undefined.

Expected Results:  
"My String"
(Reporter)

Comment 1

10 years ago
Created attachment 292280 [details]
A test case

Comment 2

10 years ago
This is the intended behavior of the forEach method.

There is an optional second parameter of forEach if you want to override the "this" object inside the callback. Check:

http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Array:forEach
Status: UNCONFIRMED → RESOLVED
Last Resolved: 10 years ago
Resolution: --- → INVALID

Updated

10 years ago
Component: General → JavaScript Engine
OS: Linux → All
Product: Firefox → Core
Hardware: PC → All

Updated

10 years ago
QA Contact: general → general
v.
Status: RESOLVED → VERIFIED
You need to log in before you can comment on or make changes to this bug.