本文介绍了创建一个像“$”一样的jQuery目的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  MyVar(parameter).functionToPerform();我的最终目标是能够做到这样的事情。 

足够愚蠢的是,即使在阅读了如何声明变量之后,查看jQuery代码,.. 。我仍然无法控制它。



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

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


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

var test = new MyClass();
test.print(); //作品
console.log('Moving:'+ test('azerty')。move()); // Type property error


解决方案

jQuery()既是一个包含全局方法的模块,也是一个构造函数。如果需要,它会自动调用构造函数。如果我们没有使用新的关键字进行调用,那么这个不会使用构造, MyClass的。我们可以检测它,并在构造函数模式中调用该函数。一旦我们这样做了,那么这个将会是 MyClass 的一个实例,我们可以开始向它添加东西。 p>

  var MyClass = function(context){
//如果调用函数而不作为构造函数调用,则
//然后调用我们的构造函数。
if(this .__ proto __。constructor!== MyClass){
return new MyClass(context);
}

//保存上下文
this.context = context;

//方法...
this.print = function(){
return打印;
}

this.move = function(){
return this.context;
}
};
$ b $('#output')。append('< li> print():'+ MyClass()。print()+'< / li>');
$('#output')。append('< li> move():'+ MyClass('azerty')。move()+'< / li>');
$('#output')。append('< li> context:'+ MyClass('azerty')。context +'< / li>');


My end goal is being able to do something like this:

MyVar(parameter).functionToPerform();

Silly enough, even after reading up on how variables are declared, looking at the jQuery code, ... I still can't get my head around it.

This is what I've tried so far, but it fails:

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
解决方案

jQuery() is both a module with global methods, and a constructor. It automatically calls a constructor if it needs to. If we are not called with a new keyword, then this will not have been constructed with MyClass. We can detect that and call the function in constructor mode instead. Once we do that, then this will be an instance of MyClass and we can start adding stuff to it.

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>');

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

这篇关于创建一个像“$”一样的jQuery目的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 04:30