javascript:作为对象或函数传递

use*_*672 5 javascript jquery frameworks function object

我的问题很奇怪,它与我在jQuery中看到的东西有关,但到目前为止我一直无法重新创建它.

在jQuery中你可以这样做

jQuery('div').append
Run Code Online (Sandbox Code Playgroud)

要么

jQuery.ajax
Run Code Online (Sandbox Code Playgroud)

我正在制作的应用程序需要类似的语法,我注意到你使用新的喜欢

var that=new function(){
}
Run Code Online (Sandbox Code Playgroud)

你可以用这个来调用函数,没有(),但在某些情况下我会需要它.

原因是我需要选择一个dom元素,就像jQuery一样.

that('[data-something="this"]').setEvent('click',functin(){})
Run Code Online (Sandbox Code Playgroud)

有些人自动这样做:

that.loadIt('this','[data-something="that"]') 
Run Code Online (Sandbox Code Playgroud)

这样做的原因是dom元素在外部加载并被推送,然后脚本在继续之前等待它准备就绪.这样做对我来说无论如何似乎是最干净的方式来获得这个功能(我编写一个完整的javascript框架,所以我避免库来保持脚本快速)

Roc*_*mat 5

函数是对象,可以具有属性,就像其他对象一样.因此,您可以向这样的函数添加属性:

function myFunc(){}
myFunc.someFunc = function(){}
Run Code Online (Sandbox Code Playgroud)

如果你使用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
Run Code Online (Sandbox Code Playgroud)


gra*_*ing 5

功能是对象.

只需摆脱new,并直接添加属性that.

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

that.loadit = function() {
    // do other work
}
Run Code Online (Sandbox Code Playgroud)

既然你正在尝试实现像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);
Run Code Online (Sandbox Code Playgroud)