1

I was trying to call .call Function prototype method on document.attachEvent in IE7. But it is showing as undefined. I have also checked typeof document.attachEvent, is should show as function but it is object. Can someone explain it why?

document.attachEvent.call(this, 'onclick', function () {});

Getting this error

Error: Object doesn't support this property or method
Andrew Li
  • 55,805
  • 14
  • 125
  • 143
hemkaran_raghav
  • 1,346
  • 11
  • 25
  • 1
    Why do you need to set a specific `this` when calling `attachEvent`? Feels like an X/Y problem. I've answered Y ("What's up with `attachEvent`?) but I suspect you really need an answer to X, the thing that made you want to do this... – T.J. Crowder Dec 07 '16 at 13:36
  • Hi, @T.J.Crowder, I was adding too many events at once, so don't want replicate code twice, one with `document.addEventListener` and one with `document.attachEvent`. So just assigning a local variable to these function, and adding events using `.call`. Anyway, I will find another methoda. – hemkaran_raghav Dec 07 '16 at 14:58
  • I'd use a wrapper method to normalize things, something like [this version of `hookEvent`](http://stackoverflow.com/questions/23799296/js-li-tag-onclick-not-working-on-ie8/23799448#23799448), which handles the various issues with `attachEvent` (like the `"on"` part, the fact that event objects on obsolete browsers like that don't have `preventDefault` or `stopPropagation` [though they have the feature, just not the standard API], etc.). – T.J. Crowder Dec 07 '16 at 15:02

1 Answers1

1

Host-provided functions are not required to be proper JavaScript functions, so long as they can be called. That means they aren't required to inherit from Function.prototype (and thus may not have call or apply, which come from Function.prototype) and typeof may not identify them as functions (because from a JavaScript perspective, while they're callable, they're not functions).

Not all obsolete browsers made functions proper functions, including IE7.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875