我正在查看一些伪 jquery 代码,尽管我大部分都理解this
,但某些实现令人困惑。我遇到了这个伪代码,它旨在解释 jQuery 的工作原理:
(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"
对我来说,(!(foo的this实例))
中的this
或this.myArg = arg;
中的内容并不是很明显> 是。
我的初步印象是,每次运行 foo
实例时都会引用此代码,即 foo("bar").myPlugin();
。
偏离这个假设,this
通常指的是拥有该方法的对象,但在这种情况下,如果 foo
拥有 this
(了解 foo
对于 jQuery
来说是伪的),jQuery.myArg = arg
并没有多大意义。这意味着每次您调用 foo
即 foo("bar").myPlugin();
时,它都会实例化 foo.bar
并进一步底部的示例,foo.bar.myPlugin
是从 foo
实例化的实际属性?
同时,this instanceof foo
,即。 jQuery instanceof jQuery
似乎是多余的。
我在这里缺少什么?感谢任何帮助/指示。
最佳答案
tl;博士
foo
是一个构造函数,我们确保它始终像这样调用。
说明
foo
是一个构造函数。当使用 new
关键字调用时,foo
函数的主体将在 foo
类的新实例的上下文中执行(this
将指向这个新实例)。所以:
this instanceof foo === true
当调用而不new
关键字时,上下文将是window
并且通常不会创建新对象。
通过
if (!(this instanceof foo))
return new foo(arg);
我们确保即使省略 new
关键字,我们也会返回 foo
的新实例。
关于javascript - jQuery 结构和理解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30281089/