我编写了一个函数,我以为我只需要处理一个对象,但结果发现我需要的不止一个。
var Helper = (function () {
return {
el: null
init: function(el) {
this.el = el;
}
doStuff: function(){
// Modify this.el in someway
}
};
}());因此,我只需在页面加载时执行Helper.init(el),然后在需要时运行Helper.doStuff()。
现在我有三个元素需要这个功能。
我的第一个想法是让它做Helper.init([el1,el2,el3]),让它在一个元素数组上工作,但是我可能想要分别对待每个元素。
我认为最好的方法可能是将Helper变成一个带有原型的“类”,但我有点准时,所以我正在寻找一种方法来制作一个包装器来完成我所需要的。
我在想,我只需要接受这个函数,而不是立即执行它,然后以某种方式将该函数存储到一个原型函数中,并以这种方式使用它。
寻找关于如何以最小的代码更改来最好地做到这一点的想法。
发布于 2017-09-28 14:44:47
我在想最好的方法可能是把“帮手生活”变成一个有原型的“类”,但我的时间有点紧……
我不指望会花很长时间。
我在想,我只需要接受这个函数,而不是立即执行它,然后以某种方式将该函数存储到一个原型函数中,并以这种方式使用它。 寻找关于如何以最小的代码更改来最好地做到这一点的想法。
类模式只是JavaScript中的一种模式,您可以像使用它一样使用这个Helper作为其他对象的原型,这与您的“最小更改”要求相匹配。只需使用Object.create
var helper1 = Object.create(Helper);
helper1.init(el);
var helper2 = Object.create(Helper);
helper2.init(el2);
var helper3 = Object.create(Helper);
helper3.init(el3);
// ...
helper1.doStuff();
helper2.doStuff();
helper3.doStuff();如果将return this;添加到init末尾,则可以更简洁:
var helper1 = Object.create(Helper).init(el);
var helper2 = Object.create(Helper).init(el2);
var helper3 = Object.create(Helper).init(el3);
// ...
helper1.doStuff();
helper2.doStuff();
helper3.doStuff();活生生的例子:
var Helper = (function () {
return {
el: null,
init: function(el) {
this.el = el;
return this;
},
doStuff: function(){
this.el.style.color = "green";
this.el.style.fontWeight = "bold";
}
};
}());
var helper1 = Object.create(Helper).init(document.getElementById("el1"));
var helper2 = Object.create(Helper).init(document.getElementById("el2"));
var helper3 = Object.create(Helper).init(document.getElementById("el3"));
// ...
setTimeout(function() {
helper1.doStuff();
}, 400);
setTimeout(function() {
helper2.doStuff();
}, 800);
setTimeout(function() {
helper3.doStuff();
}, 1200);<div id="el1">el1</div>
<div id="el2">el2</div>
<div id="el3">el3</div>
您甚至可以继续在第一个Helper上直接使用el,进一步减少代码更改,尽管我不建议这样做。
或者,将它封装在一个返回它的函数中(这里我还包括了对init的更改):
function getHelper() {
var Helper = (function () {
return {
el: null,
init: function(el) {
this.el = el;
return this; // <============== Added
},
doStuff: function(){
// Modify this.el in someway
}
};
}());
return Helper;
}那么,对于你的三个地方,你需要它:
var helper1 = getHelper().init(el);
var helper2 = getHelper().init(el2);
var helper3 = getHelper().init(el2);
// ...
helper1.doStuff();
helper2.doStuff();
helper3.doStuff();附带注意:你不需要生活无论如何,除非你有东西,其中没有显示以外的对象初始化.
发布于 2017-09-28 14:44:33
刚刚重写了代码:
function Helper (el) {
this.el = el;
}
Helper.prototype = {
doStuff: function(){
// Modify this.el in someway
}
};
var helper1 = new Helper(el1);
var helper2 = new Helper(el2);
var helper3 = new Helper(el3);
helper1.doStaff();
helper2.doStaff();
helper3.doStaff();发布于 2017-09-28 14:50:53
另一种方法是从arguments对象检索参数:
var Helper = (function () {
return {
el: null
init: function() {
this.el = Array.from(arguments)
}
doStuff: function(){
this.el.forEach(el => {
// Modify el in someway
});
}
};
}());https://stackoverflow.com/questions/46471912
复制相似问题