1

I used function() as class and I create some propeties using this. scope:

function field(newMaxX, newMaxY) {
    this.maxX = newMaxX;
    this.maxY = newMaxY;
}

But this caused this error:

Uncaught TypeError: Cannot set property 'maxX' of undefined

I have already write project with same using of function without error.

function snake(nX, nY, nScore, nDirection, maxX, maxY, cellSize) {
    this.cells = [];
    this.score = nScore;
    ...
}

Also JQuery points out at this problem:

jQuery.Deferred exception: Cannot set property 'maxX' of undefined TypeError: Cannot set property 'maxX' of undefined

I don't know how to fix that. Please help.

2
  • This code is completely fine. You can simply paste it inside your console and see that it works fine. Can you please share the code where you call it? The error should be somewhere else Commented Aug 15, 2017 at 20:50
  • 2
    are in instantiating your snake function with the new keyword somewhere or applying the context via .call, .apply, or .bind methods? I think you need to edit and provide more information. (as an aside, if you're declaring a class, I'm talking about snake, it's best practice to captialize the name, e.g. function Snake(){}) Commented Aug 15, 2017 at 20:52

1 Answer 1

1

Ok I find the problem. I just forget to use new keyword:

gameArea = field(parseInt(MAX_X / CELL_SIZE), parseInt(MAX_Y / CELL_SIZE));

That doesn't work but this does:

gameArea = new field(parseInt(MAX_X / CELL_SIZE), parseInt(MAX_Y / CELL_SIZE));

Thank you for your comments.

Sign up to request clarification or add additional context in comments.

4 Comments

Here's a trick to help you avoid forgetting to call new
@theRadek - One thing you should definitely do, whether you use the trick Juan mentioned or not, is to follow the standard JavaScript convention and begin constructor names with a capital letter and all other functions with a lowercase letter. When you do this consistently, the capital letter will become a reminder to use new. So this function should be named Field() instead of field(). Then when you see a bare call to Field() without new, it will just look wrong, and conversely, if you see new field(), that will also look wrong.
That will also make it easier for people to read your code, since most JavaScript programmers will expect to find constructors named with a capital letter.
@MichaelGeary Also note that if the OP uses capital letters at the beginning of constructors, they can use linting (eslint.org/docs/rules/new-cap) to help you find places where constructors are called without new

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.