1

index.html

<body>
    <canvas id ="mainCanvas" width = "400" height = "400"></canvas>
    <script src ="script.js"></script>
    <script src ="test.js"></script>

</body>

test.js

var canvas = document.getElementById("mainCanvas")
var context = canvas.getContext("2d")

var array = [
    context.fillRect
]

array[0](10,10,10,10)

It says:

Uncaught TypeError: Illegal invocation

Normally this context.fillRect(10,10,10,10) works...

So Why can't i call that reference from array?

2
  • why do you need to store that same function in array multiple time ? Commented Jan 31, 2016 at 18:58
  • Just testing functionality Commented Jan 31, 2016 at 19:01

1 Answer 1

2

The problem here is actually context. When you type array[0] you are in the context of that function object (a function is an object in javascript). But you want to be in context of context variable. So there are two solutions

var canvas = document.getElementById("mainCanvas")
var context = canvas.getContext("2d")

var array = [
function(params) {
context.fillRect(params)
}
]

array[0](10,10,10,10)

or second method using call

var canvas = document.getElementById("mainCanvas")
var context = canvas.getContext("2d")

var array = [
context.fillRect
]

array[0].call(context,10,10,10,10)
Sign up to request clarification or add additional context in comments.

1 Comment

Wow thanks ;) How is it i cant invoke that without that function(params) Cuz its invoking objects'function?

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.