javascript - 在带有原型(prototype)的 Javascript 中使用此关键字?

标签 javascript this prototype jasmine

当我尝试在我的 Javascript 原型(prototype)中使用 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);
  });
});

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

最佳答案

问题出在这部分代码。

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

只是没有定义“数组”。应该有效的代码是

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

关于javascript - 在带有原型(prototype)的 Javascript 中使用此关键字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9960807/

相关文章:

javascript - CORS header ‘Access-Control-Allow-Origin’ 与 Ajax 请求上的 ‘(null)’ 不匹配

javascript - 在表行上使用 .remove 会产生显示样式 :none

javascript - 在循环中如何引用主 "this"?

javascript - 如何在 Javascript (ES6) 中正确定义子类构造函数?

sql - 快速构建源自 SQL 数据库的 Web 图表原型(prototype)的方法

javascript - 错误: [ngRepeat:iexp] Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '(name,surname)in controller.students'

javascript - Javascript 可以检测移动设备是否静音吗?

javascript - React JS : Function undefined when called in . map 函数

javascript - 如何为数组创建方法作为javascript中对象的属性?

javascript - js : trigger function after a bunch of events were called