在带有原型的Javascript中使用此关键字

Using this keyword in Javascript with prototypes?

本文关键字:关键字 Javascript 原型      更新时间:2023-09-26

当我尝试在我的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关键字在这种情况下是正确的,还是我没有得到的原型有错误?谢谢

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

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

只是没有定义"array"。应该工作的代码是

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