0

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

2 Answers 2

2

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 add function:

function add(f, fun) {
    ob[f] = fun; //No invoking parentheses!
}

Here's an updated fiddle.

If you look at the console in your original fiddle you get a hint of what's going wrong:

Uncaught TypeError: Property 'hi' of object #<Object> is not a function

Sign up to request clarification or add additional context in comments.

1 Comment

You helped big, since now I finally fixed an issue I had with the library im building
1

Add your function as a property of your object :

ob['hi'] = function() {
    alert('hello')
};

or

ob[funname] = fun;

if the function was defined elsewhere.

Don't write a add function just to set a property. Replacing a standard feature of the language by a custom setter isn't going to make the code more readable.

And don't forget that you can define classes in javascript :

function Rect(x,y,w,h){
    this.x = x;
    this.y = y;
    this.w = w;
    this.h = h;
}

Rect.prototype.contains = function(x, y) {
    return x>=this.x && x<=this.x+this.w && y>=this.y && y<=this.y+this.h;
};

All objects created as new Rect(0, 1, 2, 3) have the contains function.

2 Comments

Thanks for the answer but I will need to set more than one property and I will want to do this with a function
Apart for homework, I don't see a reason to use a function to replace a standard feature of the language. If you're building a library, follow best practices.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.