在Javascript中使用此关键字与原型?

时间:2012-04-01 00:06:57

标签: javascript this prototype jasmine

当我尝试在我的Javascript原型中使用this时:

Array.prototype.sample = function() {
  return this[Math.floor (Math.random() * this.length )];
}

除了实施我的测试(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);
  });
});

我的测试失败了。这些方法最初是使用参数处理原型内部this关键字的函数,但由于这将在一个小的Javascript库中,我宁愿将其作为原型实现。在此上下文中this关键字是否正确,或者我没有得到原型的错误?感谢。

1 个答案:

答案 0 :(得分:2)

问题在于代码的这一部分。

Array.prototype.sample = function() {
   return this[Math.floor (Math.random() * array.length )];
}

没有定义'数组'。应该有效的代码是

Array.prototype.sample = function() {
   return this[Math.floor (Math.random() * this.length )];
}