2012-04-01 93 views
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关键字是否正确,或者我没有收到原型错误?谢谢。

+0

* ReferenceError:array is not defined * – 2012-04-01 00:14:28

+0

@CrescentFresh固定,但测试仍然失败。它说:'TypeError:Object foo,bar,baz,qux没有方法'sample'。 – beakr 2012-04-01 00:21:48

+0

请修正您的问题以显示更新的代码。 – kojiro 2012-04-01 00:23:29

回答

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)]; 
} 
+0

问题解决了,以前代码中的多个错误位于同一个文件中。现在应该马上恢复。谢谢您的帮助。 – beakr 2012-04-01 00:28:19