2
当我尝试使用this
在我的JavaScript的原型就像这样:在Javascript中使用此关键字与原型?
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
关键字是否正确,或者我没有收到原型错误?谢谢。
* ReferenceError:array is not defined * – 2012-04-01 00:14:28
@CrescentFresh固定,但测试仍然失败。它说:'TypeError:Object foo,bar,baz,qux没有方法'sample'。 – beakr 2012-04-01 00:21:48
请修正您的问题以显示更新的代码。 – kojiro 2012-04-01 00:23:29