[英]Correct way to override this JavaScript class method
当 JavaScript 类方法按照下面的方式设置后,我应该如何最好地覆盖它。 在这个片段中,如果我想覆盖另一个 JS 文件中的_other
方法,在这个文件之后加载,正确的方法是什么?
var review = {}; "use strict"; (function ($) { review.list = { _init: function () { // The code I want to leave intact }, _other: function () { // The code I want to override }, init: function () { $(document).ready(function () { review.list._init(); review.list._other(); }); } }; review.list.init(); })(jQuery);
您可以只分配给review.list._other
。 如果您想访问以前的版本,请先获取:
var oldOther = review.list._other;
review.list._other = function() {
// Your new code here, perhaps calling oldOther if you like
console.log("The new other code ran.");
};
例子:
// The original file var review = {}; "use strict"; (function($) { review.list = { _init: function() { // The code I want to leave intact }, _other: function() { // The code I want to override }, init: function() { $(document).ready(function() { review.list._init(); review.list._other(); }); } }; review.list.init(); })(jQuery); // Your file after it (function($) { var oldOther = review.list._other; review.list._other = function() { // Your new code here, perhaps calling oldOther if you like console.log("The new other code ran."); }; })(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
你真的很幸运它是这样写的。 它很容易被写成这样你就不能覆盖_other
......
有点跑题了,但你已经在下面问了:
实际上,这种类结构对您来说是否合理? 尝试涉足更多的 OOP JS
我不知道你的设计限制,所以对接下来的任何事情都持保留态度......我应该注意到那里根本没有“类”(无论是在 ES5 和更早的意义上,还是在 ES2015 和更高的意义上),只是一个对象。 (这很好。)但看起来_init
和_other
是私有的; 它们可以是真正的私有而不是伪私有而不需要任何成本——除非那样你就无法覆盖_other
! :-) 另外,我将允许整体控制代码确定初始化何时发生,而不是在ready
。 (另外,在纯粹的风格注释上,我根本不同意这种两个空格缩进的废话,所以许多 l33t 类型似乎正在推广。如果您的代码嵌套如此之深以至于只使用两个空格作为缩进是必要的,它需要重构;在我看来,四个空格是一个很好的清晰的缩进,不会太大以至于将您的代码从右侧推开。)
所以如果需要 ES5,像这样:
(function($) {
var list = {
init: function() {
_init();
_other();
}
};
function _init () {
// Can use `list` here to refer to the object
}
function _other() {
// Can use `list` here to refer to the object
}
review.list = list;
})(jQuery);
...但同样,这使得覆盖_other
成为不可能(好吧,不合理)。
或者,如果 ES2015 及更高版本没问题(对于这么短的代码,差异很小):
(function($) {
let list = {
init() {
_init();
_other();
}
};
function _init () {
// Can use `list` here to refer to the object
}
function _other() {
// Can use `list` here to refer to the object
}
review.list = list;
})(jQuery);
只需在下面添加您的新覆盖......它会起作用......
var review = {}; "use strict"; (function($) { review.list = { _init: function() { console.log('I\\'m init') }, _other: function() { //This original will be overridden console.log('Original') }, init: function() { $(document).ready(function() { review.list._init(); review.list._other(); }); } }; review.list.init(); })(jQuery); review.list._other = function() { console.log('overridden') }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.