Javascript: passing as an object or function

My question is rather strange, this is due to what I saw in jQuery, but so far I have not been able to recreate it.

in jQuery you can go like this:

jQuery('div').append

or

jQuery.ajax

the application I am creating will require a similar syntax, I notice that if you use a new one, for example

var that=new function(){
}

you can only call a function with this, without (), but in some cases I will need it.

The reason for this are some functions, I need to select the dom element just like jQuery.

that('[data-something="this"]').setEvent('click',functin(){})

and some automatically do it like this:

that.loadIt('this','[data-something="that"]') 

, dom , script , , . , ( javascript, )

+5
3

- .

new that.

var that = function() {
    // do some work
}

that.loadit = function() {
    // do other work
}

- jQuery, that .

;(function(global) {

       // function to be publicly exposed
    var that = function(foo, bar) {
        return new MyLibrary(foo, bar);
    }

       // publicly expose the function
    global.that = that;

       // use the function as a namespace for utilities
    that.loadit = function() {
        // do other work
    }

       // The actual constructor function, like the internal jQuery constructor
    MyLibrary(foo, bar) {
        // constructor function
    }

       // Prototypal inheritance of objects created from the constructor
    MyLibrary.prototype.setEvent = function() {
        // do some work
        return this;  // allows for method chaining
    };
    MyLibrary.prototype.otherMethod = function() {
        // do something else
        return this;  // allows for method chaining
    };
})(this);
+5

- , . , , :

function myFunc(){}
myFunc.someFunc = function(){}

new myFunc, someFunc, prototype.

, - :

function myFunc(){
    // This lets you do "myFunc()" instead of "new myFunc()"
    if (!(this instanceof myFunc)) {
        return new myFunc();
    }
    else{
        this.val = 0;

        this.setVal = function(x){
            this.val = x;
            // for function chaining
            return this;
        }

        this.getVal = function(){
            return this.val;
        }
    }
}

// This function is not part of the prototype
myFunc.test = function(){
    alert('hi');
}

// Some tests
var obj = myFunc();
obj.setVal(12).getVal(); // 12

myFunc.test();

obj.test(); // Error: 'test' is not a function

myFunc.getVal(); // Error: 'getVal' is not a function
+5
$.fn.loadIt=function(var1,var2) {
  // $(this) is automatically passed
  // do stuff
}

name it like that

$('#element').loadIt('a variable','another variable');
0
source

All Articles