Q:

Using this keyword in Javascript with prototypes?

When I try to use this in my Javascript prototype like so:
Array.prototype.sample = function() {
  return this[Math.floor (Math.random() * this.length )];
}

As well as implement my tests (Jasmine):
describe('sample()', function() {
  it('returns a random item of an array', function() {
    orig_array = ['foo', 'bar', 'baz', 'qux'];
    sampled_word = orig_array.sample(); 
    expect(orig_array).toContain(sampled_word);
  });
});

My test fails. These methods were originally functions using arguments to process the this keyword inside of the prototype, but due to the fact that this is going to be in a small Javascript library, I'd rather implement it as a prototype. Is the this keyword correct in this context, or is there a error with the prototype I'm not getting? Thanks.

A:

The problem is in this part of the code.
Array.prototype.sample = function() {
   return this[Math.floor (Math.random() * array.length )];
}

Simply 'array' is not defined. The code which should work is
Array.prototype.sample = function() {
   return this[Math.floor (Math.random() * this.length )];
}

