0

So basically I have a JS function which looks like:

var myFunc = function () {
  var settings = {/*my default settings */};  
  function otherFunc(arg){
    /*do stuff*/
  }
  otherFunc(settings);
  return {settings:settings};
}()

Now, using the console I can call myFunc.settings and it will perfectly output these, however I want to user to overwrite the default settings such as:

<script src="myfunc.js"></script>
<script>myFunc.settings = {/*overwrite some settings*/};</script>

Now myFunc.settings are the new settings, yet the function still uses the 'old' settings. Any clue how I would go about this?

Thanks!

6
  • I would look into creating an object with mutators/getters. Commented Sep 8, 2013 at 22:41
  • what do you mean by "the function still uses the old setting"? Commented Sep 8, 2013 at 22:50
  • the myFunc is actually not a function, it's the return value of your anonymous function. Commented Sep 8, 2013 at 22:54
  • @grape_mao When the function is called, it uses the default settings and not the settings that has been set afterwards Commented Sep 8, 2013 at 23:00
  • because like I said, your myFunc is the return value of that function. You change a value of the return value, of course the function who finished execution won't see it. Have a look at Kyle Weller's answer, he defines a constructor, you can then create new object with it. Commented Sep 8, 2013 at 23:06

3 Answers 3

1

I don't know why myFunc is even a function. It should be an object:

var myThing = {
  settings: {/*my default settings */};  
}

Then you can call myThing.settings to get the default settings.

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

Comments

0

You can make it a property (and not local) with this:

function MyFunc () {
  this.settings = {/*my default settings */};  
};
MyFunc.settings = { foo: 'bar' };
console.log(MyFunc.settings); // Object {foo: 'bar'}

That may expose more than you really want, so you might consider allowing options to be passed when you're constructing whatever you're creating:

function MyFunc (options) {
  var defaults = { foo: 'baz' };
  var settings = /* merge defaults and options */;

  /* You probably don't even need to expose settings now. */
};
var instance = new MyFunc({ foo: 'bar' });

1 Comment

Thanks. Using the 2nd alternative now. Works like a charm ;-)
0

have an argument where you can pass in settings, if the argument is not supplied, revert to default settings:

var myFunc = function (newSettings) {
  var settings = newSettings || {/*my default settings */};  
  //do something
  return {settings:settings};
}

Comments

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.