jQuery结构并理解这一点

时间:2015-05-16 21:45:36

标签: javascript jquery

我正在浏览一些伪jquery代码 - 虽然我理解public void onClick(View v) { switch(on) { case 0: startService(new Intent(this, BluetoothScanner.class)); on = 1; break; case 1: stopService(new Intent(...); on = 0; break; } } }); 大部分内容,但有些实现令人困惑。我遇到了这个伪代码,这是为了解释jQuery是如何工作的:

this

对我来说,(function() { var foo = function(arg) { // core constructor // ensure to use the `new` operator if (!(this instanceof foo)) return new foo(arg); // store an argument for this example this.myArg = arg; //.. }; // create `fn` alias to `prototype` property foo.fn = foo.prototype = { init: function () {/*...*/} //... }; // expose the library window.foo = foo; })(); // Extension: foo.fn.myPlugin = function () { alert(this.myArg); return this; // return `this` for chainability }; foo("bar").myPlugin(); // alerts "bar" this(!(this instance of foo))的内容并不是很明显。

我的初步印象是每次运行this.myArg = arg;的实例时都会引用此代码,即foo

假设这个假设,foo("bar").myPlugin();通常是指拥有该方法的对象,但在这种情况下,如果this拥有foo(理解this是伪的对于foo),jQuery并没有多大意义。这意味着每次调用jQuery.myArg = argfoo它实例化foo("bar").myPlugin();并进一步在底部的示例时,foo.bar是从foo.bar.myPlugin实例化的实际属性?

同时,foo,即。 this instanceof foo似乎是多余的。

我在这里缺少什么?感谢任何帮助/指导。

1 个答案:

答案 0 :(得分:2)

TL;博士

foo是一个构造函数,我们确保它总是这样调用。

解释

foo是一个构造函数。当使用new关键字调用时,foo函数的主体将在foo类的新实例的上下文中执行(this将指向此新实例)。所以:

this instanceof foo === true

没有 new关键字时,上下文将为window,通常不会创建新对象。

if (!(this instanceof foo))
  return new foo(arg);

我们确保即使遗漏了new个关键字,我们也会返回foo的新实例。

相关问题