this._super()
https://learn.jquery.com/jquery-ui/widget-factory/extending-widgets/
https://api.jqueryui.com/jquery.widget/#method-_super
https://johnresig.com/blog/simple-javascript-inheritance/
To make the parent's methods available, the widget factory provides two methods - _super()
and _superApply()
.
Using _super()
and _superApply()
to Access Parents
_super()
and _superApply()
invoke methods of the same name in the parent widget. Refer to the following example. Like the previous one, this example also overrides the open()
method to log "open"
. However, this time _super()
is run to invoke dialog's open()
and open the dialog.
$.widget( "custom.superDialog", $.ui.dialog, { open: function() { console.log( "open" ); // Invoke the parent widget's open(). return this._super(); } }); $( "<div>" ).superDialog();
proxiedPrototype[ prop ] = (function() {
var _super = function() {
return base.prototype[ prop ].apply( this, arguments );
},
_superApply = function( args ) {
return base.prototype[ prop ].apply( this, args );
};
return function() {
var __super = this._super,
__superApply = this._superApply,
returnValue;
this._super = _super;
this._superApply = _superApply;
returnValue = value.apply( this, arguments );
this._super = __super;
this._superApply = __superApply;
return returnValue;
};
})();
jquery ui widget 源码分析
//在传入的ui原型中有方法调用this._super 和this.__superApply会调用到base上(最基类上)的方法 127 $.each(prototype, function(prop, value) { 128 //如果val不是function 则直接给对象赋值字符串 129 if (!$.isFunction(value)) { 130 proxiedPrototype[prop] = value; 131 return; 132 } 133 //如果val是function 134 proxiedPrototype[prop] = (function() { 135 //两种调用父类函数的方法 136 var _super = function() { 137 //将当期实例调用父类的方法 138 return base.prototype[prop].apply(this, arguments); 139 }, 140 _superApply = function(args) { 141 return base.prototype[prop].apply(this, args); 142 }; 143 return function() { 144 var __super = this._super, 145 __superApply = this._superApply, 146 returnValue; 147 // console.log(prop, value,this,this._super,'===') 148 // debugger; 149 //在这里调用父类的函数 150 this._super = _super; 151 this._superApply = _superApply; 152 153 returnValue = value.apply(this, arguments); 154 155 this._super = __super; 156 this._superApply = __superApply; 157 // console.log(this,value,returnValue,prop,'===') 158 return returnValue; 159 }; 160 })(); 161 });