(function(){})()的用法与优点_javascript技巧

WBOY
Release: 2016-05-16 19:16:59
Original
1184 people have browsed it

在google的ad的js里面,发现有类似这样的语句
//我用alert("test")代替里面的语句

(function(){alert("test")})()
测试了一下,类似直接执行

alert("test")
那这个用法是有什么好处么?希望大家说一下啊!

function xx(){...}
相当于
var xx;
xx=function(){...}

function(){....}返回一个Function对象
(Function对象)()就是调用该函数了

直观的好处是把几条需要顺序执行的语句组织成一个单元,使逻辑清晰,又不用为它取名字
可能出于节约的考虑:该匿名函数像一个临时变量,执行后可以被立即销毁,当然连同其中的局部变量

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!