5

私の質問はかなり奇妙です.jQueryで見たものと関係がありますが、これまでのところ私はそれを再現できませんでした.

jQueryでは、このように行くことができます

jQuery('div').append

また

jQuery.ajax

私が作成しているアプリケーションには同様の構文が必要です。

var that=new function(){
}

() なしで、それだけで関数を呼び出すことができますが、場合によってはそれが必要になります。

この理由は、jQuery のように dom 要素を選択する必要があるいくつかの関数です。

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

自動的にそうするものもあります:

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

これは、dom 要素が外部から読み込まれてプッシュされ、スクリプトが準備が整うまで待機してから続行するためです。とにかく、この方法でこの機能を取得するのが最もクリーンな方法のように思えます(私は完全なJavaScriptフレームワークをコーディングしているので、スクリプトを高速に保つためにライブラリを避けています)

4

3 に答える 3

5

関数はオブジェクトであり、他のオブジェクトと同様にプロパティを持つことができます。したがって、次のようにプロパティを関数に追加できます。

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

の一部ではないためnew myFunc、結果のオブジェクトを使用する場合はありません。someFuncprototype

したがって、次のようなものを作成できます。

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
于 2012-09-12T18:42:43.710 に答える
5

関数はオブジェクトです。

を取り除き、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);
于 2012-09-12T18:42:55.090 に答える
0
$.fn.loadIt=function(var1,var2) {
  // $(this) is automatically passed
  // do stuff
}

このように呼びます

$('#element').loadIt('a variable','another variable');
于 2012-09-12T18:42:33.743 に答える