当我尝试在我的 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/