创建一个像"$"对象的jQuery

ske*_*rit 11 javascript function

我的最终目标是能够做到这样的事情:

MyVar(parameter).functionToPerform();
Run Code Online (Sandbox Code Playgroud)

很傻,即使在阅读了如何声明变量之后,查看jQuery代码,......我仍然无法理解它.

这是我到目前为止尝试过的,但它失败了:

var MyClass = function(context) {
this.print = function(){
    console.log("Printing");
}

this.move = function(){
    console.log(context);
}
};

var test = new MyClass();
test.print(); // Works
console.log('Moving: ' + test('azerty').move() ); // Type property error
Run Code Online (Sandbox Code Playgroud)

Ple*_*and 15

在我写这篇文章的时候,Squeegy的答案得票率最高:7.但这是错误的,因为它是__proto__非标准的,并且不受Internet Explorer(甚至版本8)的支持.但是,摆脱__proto__它不会让它在IE 6中运行.

这(稍微简化)是jQuery实际执行的方式(甚至在IE 6上尝试),它还包括静态方法和方法链接的示例.有关jQuery如何做的所有细节,当然你必须自己检查jQuery源代码.

var MyClass = function(context) {
    // Call the constructor
    return new MyClass.init(context);
};

// Static methods
MyClass.init = function(context) {
    // Save the context
    this.context = context;
};
MyClass.messageBox = function(str) {
    alert(str);
};


// Instance methods
MyClass.init.prototype.print = function() {
    return "Printing";
};
MyClass.init.prototype.move = function() {
    return this.context;
};

// Method chaining example
MyClass.init.prototype.flash = function() {
    document.body.style.backgroundColor = '#ffc';
    setInterval(function() {
        document.body.style.backgroundColor = '';
    }, 5000);
    return this;
};


$('#output').append('<li>print(): '+ MyClass().print() +'</li>');
$('#output').append('<li>flash().move():'+ MyClass('azerty').flash().move() +'</li>');
$('#output').append('<li>context: '+ MyClass('azerty').context +'</li>');
MyClass.messageBox('Hello, world!');
Run Code Online (Sandbox Code Playgroud)

请注意,如果您需要"私有"数据,则必须将实例方法放入MyClass.init(使用在该函数内部声明的变量)this.print = function() { ... };而不是使用MyClass.init.prototype.


Ale*_*yne 13

jQuery()既是具有全局方法的模块,也是构造函数.如果需要,它会自动调用构造函数.如果我们没有使用new关键字调用,那么this就不会构造MyClass.我们可以检测到它并在构造函数模式下调用该函数.一旦我们这样做,那么this将是一个实例,MyClass我们可以开始添加东西.

var MyClass = function(context) {
    // if the function is called without being called as a constructor,
    // then call as a constructor for us.
    if (this.__proto__.constructor !== MyClass) {
        return new MyClass(context);
    }

    // Save the context
    this.context = context;

    // methods...
    this.print = function() {
        return "Printing";
    }

    this.move = function() {
        return this.context;
    }
};

$('#output').append('<li>print(): '+ MyClass().print() +'</li>');
$('#output').append('<li>move():'+ MyClass('azerty').move() +'</li>');
$('#output').append('<li>context: '+ MyClass('azerty').context +'</li>');
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/rvvBr/1/