gpt4 book ai didi

javascript - 函数应该在 jQuery 的扩展内部还是外部?

转载 作者:可可西里 更新时间:2023-11-01 02:21:30 27 4
gpt4 key购买 nike

我正在编写我的第一个 jQuery 插件,但我不完全确定什么应该扩展声明中,什么不应该。

$.fn.myplugin = function () {
var somevar = this;
someFunc(somevar);
};
function someFunc() {/*doSomethin'*/};

$.fn.myplugin = function () {
var somevar = this;
someFunc(somevar);
function someFunc() {/*doSomethin'*/};
};

最佳答案

I'd use the first option because:

It doesn't have any negative side effects.

那是你错的地方。如果您正在使用不同的库,您可能会冒着覆盖其他人的 someFunc() 的风险,可能会破坏他们试图为您做的任何事情。一种更安全的方法是在您的代码周围封装一个闭包。

(function(){

$.fn.myplugin = function () {
var somevar = this;
someFunc(somevar);
};

function someFunc() {/*doSomethin'*/};

/* Do whatever other things you need someFunc/myplugin for */

})();

这样你的 someFunc 就不受全局命名空间的影响了。

或者,您可能希望将对象的方法暴露给外界。举个例子:

$.fn.dog = function () {

this.bark = function() {alert("Woof");};

return this;
};

var $max = new $('#myDogMax').dog();
$max.bark();

这使函数保持在对象的上下文中,但可以从外部干净地访问它。尽管这通常意味着该方法与对象有某种关联。全局编写一个 bark() 函数没有什么意义,因为通常是狗而不是浏览器窗口会这样做。

关于javascript - 函数应该在 jQuery 的扩展内部还是外部?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30477483/

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