1

I am developing a small JavaScript Framework, I need to know how to add some options to a function, so the user can set his own settings for a particular method.

This is a sample function method i have created

$.prototype = {
  setCenter: function() {

        this.e.style.position = 'absolute';
        this.e.style.top = '50%';
        this.e.style.left = '50%';
        this.e.style.marginLeft = '-50px';
        this.e.style.marginTop = '-50px';
        return this;



    }
};

I am expecting this to be developed to handle the below options sets.

*I am not using JQuery, I need a pure JavaScript Solution for this. This is an example code, maybe not the real thing , but just get the idea.

$('sampleDiv').setCenter({
              animate:true, fade:true
              });

Help me solve this problem, i appreciate anyone who tries to answer this. Thank you !

Dilusha Gonagala
  • 431
  • 4
  • 12

3 Answers3

1

Copied the code from this answer

function extend(){
    for(var i=1; i<arguments.length; i++)
        for(var key in arguments[i])
            if(arguments[i].hasOwnProperty(key))
                arguments[0][key] = arguments[i][key];
    return arguments[0];
}

This function can be used for any number of objects.

var newObj = extend(obj1, obj2, obj3, ...);

OR

var newObj = extend({}, obj1, obj2, obj3, ...); 
Community
  • 1
  • 1
Faisal Sayed
  • 783
  • 4
  • 12
1

You could implement your main function this way :

this.doSomething = function() {
    var getDefault = function(args, property, otherwise) {
            return args[property] !== undefined ? args[property] : otherwise;
    };

    this.foo = getDefault(arguments, 'foo', 42);
    this.bar = getDefault(arguments, 'bar', false);
};

So you can call it like that :

this.doSomething({foo: true});
LoremIpsum
  • 4,328
  • 1
  • 15
  • 17
1
$.prototype = {
  setCenter: function(offset) {

        this.e.style.position = 'absolute';
        this.e.style.top = '50%';
        this.e.style.left = offset + 50 + '%';
        this.e.style.marginLeft = '-50px';
        this.e.style.marginTop = '-50px';
        return this;
    }
};

Use like this

this.setcenter(23);
Ashneil Roy
  • 154
  • 5