[英]Adding properties to an object using function and bracket notation
我正在對一個基本的javascript類進行分配,但似乎無法正常工作。 我有這個單元測試:
describe('AddSixthProperty', function() {
it('should add a food property with the value of bbq using bracket notation', function() {
expect(objects.addSixthProperty()['food']).to.equal('BBQ');
});
});
我得到了一個空函數:
// don't touch this line
var mysticalAnimal = objects.mysticalAnimal();
function addSixthElement(){
return
}
所以我嘗試了這個:
var mysticalAnimal = objects.mysticalAnimal();
objects.addSixthProperty = function(){
mysticalAnimal['food'] = "bbq";
return mysticalAnimal["food"];
};
沒用 我們的測試頁沒有通過。 任何幫助是極大的贊賞!
提前致謝!
您將返回mysticalAnimal['food']
,然后測試再次嘗試訪問['food']
,因此最終會訪問undefined
'bbq'['food']
。 您只需要return mysticalAnimal
,並正確處理所有字母大小寫。 這里有一些概念證明:
var objects = (function() { var animal = { mystical: true }; return { mysticalAnimal: function() { return animal; } }; })(); var mysticalAnimal = objects.mysticalAnimal(); objects.addSixthProperty = function(){ mysticalAnimal['food'] = "bbq"; return mysticalAnimal; }; var capturedAnimal = objects.addSixthProperty(); document.getElementById('result').innerText = capturedAnimal['food'];
<p id="result" />
這是函數:
var mysticalAnimal = objects.mysticalAnimal(); objects.addSixthProperty = function(){ mysticalAnimal['food'] = "BBQ"; return mysticalAnimal; }; // Test the function console.log(objects.addSixthProperty()['food'])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.