gpt4 book ai didi

javascript - 覆盖此 JavaScript 类方法的正确方法

转载 作者:行者123 更新时间:2023-11-29 17:55:17 26 4
gpt4 key购买 nike

当按照以下设置时,我应该如何最好地覆盖 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...


有点跑题了,不过你在下面问过:

Actually, does this class structure look reasonably sensible to you? Trying to dip toes into more OOP JS

我不知道你的设计限制,所以对后面的任何东西都持保留态度......我应该注意到那里根本没有“类”(无论是在 ES5 和更早的意义上,还是在 ES2015 和更高版本中感),只是一个对象。 (这很好。)但看起来 _init_other 是私有(private)的;它们可以是真正私有(private)的而不是伪私有(private)的,而无需任何成本——除非那样你就无法覆盖 _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);

关于javascript - 覆盖此 JavaScript 类方法的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39708638/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com