我正在创建某种小部件,我需要某种
<script src="https://cdn.dhtmlx.com/scheduler/edge/dhtmlxscheduler.js"></script>
<script src="https://cdn.dhtmlx.com/scheduler/edge/ext/dhtmlxscheduler_tooltip.js"></script>
<link rel="stylesheet" href="https://cdn.dhtmlx.com/scheduler/edge/dhtmlxscheduler.css">
<div id="scheduler_here" class="dhx_cal_container" style='width:100%; height:100vh;'>
<div class="dhx_cal_navline">
<div class="dhx_cal_prev_button"> </div>
<div class="dhx_cal_next_button"> </div>
<div class="dhx_cal_today_button"></div>
<div class="dhx_cal_date"></div>
<div class="dhx_cal_tab" name="day_tab" style="right:204px;"></div>
<div class="dhx_cal_tab" name="week_tab" style="right:140px;"></div>
<div class="dhx_cal_tab" name="month_tab" style="right:76px;"></div>
</div>
<div class="dhx_cal_header">
</div>
<div class="dhx_cal_data">
</div>
</div>
其中widget = widget || {};
widget = (function() {
var p = 'some value';
function config(){
//some config actions
}
})();
var o1 = widget.config(); // do this one return an object\instance?
var o2 = widget.config(); // and this one return another instance or same as in o1 ?
(作为实例),因此它们具有不同的属性值。当我换一个时,另一个不应该改变。
o1 != o2
与php或其他OOP语言相同。
我如何使用jQuery做到这一点?
答案 0 :(得分:2)
您可以使用Javascript OOP:
function widget() {
var p = 'some_value';
this.config = function() {
// some config action
};
}
var o1 = new widget();
o1.config();
var o2 = new widget();
o2.config();
如果config()
未使用p
,您只需定义一次:
widget.prototype.config = function() {
// some config action
};
答案 1 :(得分:0)
使用Widget Factory创建jQuery小部件。这很简单。
当然,您可以实施多种方法(例如_destroy
,_setOption
和_create
)。
$(function() {
$.widget("ns.widget", { // "ns" is your namespace; "widget" can be anything
// induvidually stored values (with defaults)
options: {
p: "some value"
},
// the constructor
_create: function() {
this.element.text(this.options.p);
}
});
// create a few
$("#o1").widget({p: "some"})
$("#o2").widget({p: "other"})
$("#o3").widget()
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<div id="o1"></div>
<div id="o2"></div>
<div id="o3"></div>
&#13;
<强>的JavaScript 强>
现在您发布的代码看起来像纯JavaScript。要创建此类对象,您需要new
关键字
function Widget(p) { // constructor
this.p = p || "some value"
}
Widget.prototype = { // more functions
"print": function() {
console.log(this.p)
}
}
// create either like this
var o1 = new Widget('some')
// or
var o2 = new Widget()
o2.p = 'another'