Coming soon - Get a detailed view of why an account is flagged as spam!
view details

This post has been de-listed (Author was flagged for spam)

It is no longer included in search results and normal feeds (front page, hot posts, subreddit posts, etc). It remains visible only via the author's post history.

7
Strange behavior of variables in a factory function
Post Body

I'm making tic-tac-toe for TOP, this is a factory function for making cells:

const cell = function(token, rowIndex, colIndex) {
        let _token = token;
        const _rowIndex = rowIndex;
        const _colIndex = colIndex;

        const getToken = () => _token;
        const getRowIndex = () => _rowIndex;
        const getColIndex = () => _colIndex;
        const changeToken = (newToken) => _token = newToken;

        return {
            _token,
            getToken,
            getRowIndex,
            getColIndex,
            changeToken,
        };
    };

When I print an object and its properties, I get this seemingly contradictory behavior:

myCell = cell('bob', 1, 2);
console.log(myCell);
// Object { _token: "bob", ...}
console.log(myCell.getToken());
// 'bob' 
myCell.changeToken("jimmy");
console.log(myCell);
// Object (_token: "bob", ...};
console.log(myCell.getToken());
// 'jimmy'

Why is this happening? How can the console still show "bob" even when getToken() returns the updated value? I think it's because the _token that takes the argument value, and the _token in the returned object, are actually two different variables. Is this accurate? And is there a way to make these values consistent?

Author
Account Strength
0%
Account Age
6 years
Verified Email
Yes
Verified Flair
No
Total Karma
1,962
Link Karma
929
Comment Karma
1,015
Profile updated: 3 weeks ago
Posts updated: 2 weeks ago

Subreddit

Post Details

We try to extract some basic information from the post title. This is not always successful or accurate, please use your best judgement and compare these values to the post title and body for confirmation.
Posted
1 year ago