jQuery小部件------这是什么上下文?
在制作jQuery小部件时,您能解释一下这个的概念吗 当我在函数jQuery小部件------这是什么上下文?,jquery,jquery-ui,jquery-plugins,Jquery,Jquery Ui,Jquery Plugins,在制作jQuery小部件时,您能解释一下这个的概念吗 当我在函数\u createMyShell中创建一个变量this.shell时,为什么整个小部件都可以使用它。它不应该只对功能可用吗 或者它正在为小部件对象的上下文创建属性?请你解释一下好吗 function ($, undefined) { $.widget('hhh.myTestWidget', { version: 'alpha', _create: function () { th
\u createMyShell
中创建一个变量this.shell
时,为什么整个小部件都可以使用它。它不应该只对功能可用吗
或者它正在为小部件对象的上下文创建属性?请你解释一下好吗
function ($, undefined) {
$.widget('hhh.myTestWidget', {
version: 'alpha',
_create: function () {
this.element.addClass('hhh.myTestWidget');
this._createMyShell();
this._renderMyStuff();
//console.log(this.element);
//console.log(this.options);
},
_createMyShell: function () {
this.shell = $('<div>this is my shell</div>');
},
_renderMyStuff: function () {
this.shell.appendTo(this.element);
}
});
}(jQuery));
函数($,未定义){
$.widget('hhh.myTestWidget',{
版本:“alpha”,
_创建:函数(){
this.element.addClass('hhh.myTestWidget');
这个;
这个;
//console.log(this.element);
//console.log(this.options);
},
_createMyShell:函数(){
this.shell=$('this is my shell');
},
_renderMyStuff:函数(){
this.shell.appendTo(this.element);
}
});
}(jQuery));
即使您的代码不是小部件,this.shell=foo
也只是将一个新属性shell
添加到变量this
但是,
此
是根据函数调用的上下文确定的,jQuery UI小部件包装器确保此
始终设置为创建的包含所有显示方法的新对象。函数中的此
表示对象小部件
。小部件中的每个函数都分配给同一个对象<代码>\u createMyShell必须在小部件中声明如下:widget.prototype.\u createMyShell=function(){}
。但是我不能向你保证这是完全一样的,还有其他的可能性,但是你函数的上下文[这个
]将是小部件(一些方法,比如绑定
,调用
和应用
可以重新绑定上下文)
既然您知道
这个
是小部件对象,您可以为它分配属性,比如shell
。但是,由于其他功能附加到小部件,并且您将外壳
附加到小部件上,因此当您在所述小部件内或当您可以访问小部件对象时,您可以访问它。我想您会感到困惑,因为Javascript中的函数是对象。但是在函数中,这是对执行上下文的引用。如果你只是打电话
function doSomething() {
console.debug(this);
}
doSomething();
您将获得浏览器的窗口对象。但作为例外,当函数是对象的属性时,此
绑定到该对象。当使用new
对函数进行实例化时,函数将此
绑定到该函数。为了显示差异,下一示例中的这两个共享相同的引用:
var a = function() {
this.doSomething = function() {
console.debug(this);
}
}
var b = new a;
b.doSomething();