I am currently trying to add to an object through a function.
My code is:
var ob = {};
function add(f, fun) {
ob[f] = fun();
}
add('hi', function() {
alert('hello')
})
ob.hi()
So this is suppose to change ob to:
var ob = {
hi: function(){
alert('hello')
}
}
It does alert hello but just from the triggering of the add function (which I want to stop) and not from the ob.hi() function.
Thanks for any help. If you want you can also check the fiddle
You are executing the function and assigning its return value to the property. You need to assign a reference to the function to the property instead. Change your
addfunction:Here’s an updated fiddle.
If you look at the console in your original fiddle you get a hint of what’s going wrong: