Home  >  Article  >  Web Front-end  >  学习YUI.Ext 第二天_YUI.Ext相关

学习YUI.Ext 第二天_YUI.Ext相关

WBOY
WBOYOriginal
2016-05-16 19:17:111219browse

遇到一些JS的语法上的问题,没有理解透,恶补基本功!

 

匿名函数 An anonymous function

没有名字的就叫作“匿名函数”,像这个

function(x,y){return x+y}

没有名字当然不能直接调用,也无法调用;最多能只能把它赋值或闭包处理(闭包是什么下面再讲),如:

var sum =function(x,y){return x+y};

alert(sum(1,2));

这时候,与传统写法是等价的 function sum(x,y){return x+y}.这样的写法让人感觉更OOP,因为sum变量就包含了function...这个函数体;

还可以闭包的方式调用该函数:

(functioin(x,y){return x+y})(1,2) //返回值3

代码很简洁。注意括号的使用,形式为(exp)()。这种用法可以称作 闭包closure。
后面括号的是参数,把这些参数放进fn里面立即计算,得出一个值 3。这实际上是一个表达式的运算。没想到fn函数体也可以放进去参与运算^_^(Using function as an expression)!(基本功:表达式Expression,其含义是通过计算后,始终会返回一个值,无论这个表达式有多长)

fn还可以以参数形式传递(passing function as argument to other functions)

var main_fn = function(fn,x,y){return fn(x,y)}

var sum = function (x,y){
   return x+y;
}

alert(main_fn(sum,1,2)) // result:3

总结一下(by an IBM Engineer's article, refer to IBM website,最好用心记一记)

Functions need not have names all the time.

Functions can be assigned to variables like other values.

A function expression can be written and enclosed in parenetheses for application later.

Functions can be passed as arguments to oher funcitons.

再谈闭包,闭包的作用是形成一个定义域,举一个很白痴的例子 1+(2+3),括号部分优先运算,或者换个说法,括号里面的归为一个范围,这个范围我不理你做什么事情都是你里面做的事情,与括号外界无关(好像是废话,--我是这样想的,就是这样写的@#@),程序上的理解也是这样。js有函数定义域function scope,因此,当使用this指向一个对象出现问题的时候,可考虑使用闭包。具体例子在:http://www.svendtofte.com/code/practical_functional_js/

Statement:
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