Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Daily Tips翻译]Keeping your JavaScript out of the global scope #11

Open
Pomelo1213 opened this issue Feb 11, 2018 · 0 comments
Open
Labels
学到了知识 learning 翻译 translate

Comments

@Pomelo1213
Copy link
Owner

Source Website

2017年12月15日

Keeping your JavaScript out of the global scope (and why you want to)

这周,我们学习了关于JavaScript Scopehow to define and update variables across different types of scope

你也许想在这时候在全局作用域中声明一个函数或者变量(你想让其他的script能够使用它,例如,一个轻量级的框架。)

但是这样来说,你想在全局作用域中使用你的方法和变量。同时,如果另一个script或者另一个开发者定义了一个和你的script里面名字一模一样的函数或者变量,那将会出现重写或者造成冲突。

你可以在词法作用域中用一个函数封装你的代码。

// Wrapper for your code(封装你的代码)
var myScripts = function () {
	// Your codes goes here...
};

// Run your scripts
myScripts();

如果你想当文件运行且没有加载你的函数时代码立即运行,你可以使用一种名为立即执行函数来做这件事情。立即执行函数是(内嵌,没有名字)一个匿名函数可以立刻运行。

;(function (window, document, undefined) {
	// Your code goes here...
})(window, document);

使用两种之一可以让你的代码更强壮。

@Pomelo1213 Pomelo1213 changed the title [Daily Tip翻译]Keeping your JavaScript out of the global scope [Daily Tips翻译]Keeping your JavaScript out of the global scope Aug 21, 2018
@Pomelo1213 Pomelo1213 added 学到了知识 learning 翻译 translate labels Aug 21, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
学到了知识 learning 翻译 translate
Projects
None yet
Development

No branches or pull requests

1 participant