0

I just read the following JS code and I got 2 questions:

  1. Why isn't the container object declared as variable?
  2. What is"Array.prototype.push.apply" for?

Javascript

 Container = function(title, used) {
  this.title = title;
  this.used= !!used;
  this.callbacks = [];
 };

Container.prototype.push = function() {
    Array.prototype.push.apply(this.callbacks);
};
vuvu
  • 4,886
  • 12
  • 50
  • 73
  • 1) Because it's a mistake. Or was already declared somewhere else – Bergi Jan 20 '15 at 23:27
  • 1
    2) Have a look at [what `apply` does](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply). However, your Containers `push` method doesn't make too much sense, it's equivalent to `this.callbacks.push()` - without any arguments. – Bergi Jan 20 '15 at 23:28
  • should be .apply(this.callbacks, arguments ); – dandavis Jan 20 '15 at 23:30
  • @Bergi, 1 aint no mistake. that's how you declare Objects. – Octopus Jan 20 '15 at 23:32
  • 1
    @Octopus: There is no declaration, and there is no object. There's a function that is assigned to an undeclared variable. – Bergi Jan 20 '15 at 23:34
  • 1) is valid if the code does not have a "use strict" directive. That's one of the reasons that "use strict" is a good idea. – Lee Jenkins Jan 20 '15 at 23:37
  • 1
    to be fair, without "use strict"; in the code, we can't assume it's a mistake; some folks declare globals like that. it's likely poor practice, but i wouldn't go so far as to flag it a "mistake"... – dandavis Jan 21 '15 at 00:03

1 Answers1

0

Apply sets the invoking object within the push function. But it doesn't seem to be used correctly here. More on the invoking object, constructor functions and prototype here: https://stackoverflow.com/a/16063711/1641941

Community
  • 1
  • 1
HMR
  • 37,593
  • 24
  • 91
  • 160