2012-04-01 25 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