Showing posts with label Function. Show all posts
Showing posts with label Function. Show all posts

Sunday, June 20, 2010

relationship of constructor and prototype in javascript


var animal = function(status) {
this.status = status;
this.breathes = "yes";
this.action = function() {
console.log('flying...')
};
},
human = function() {
this.name = 'human';
},
cat = function() {
this.type = 'cat';
};

// javascript支持原型继承,这种方式比类继承更强大,类继承中一个对象可以继承结构和行为,而原型继承可以继承结构和行为之外,并可以继承一个对象的状态
// new一个animal的实例对象作为cat.prototype的原型,这个animal实例对象就成为cat的实例对象原型链上的一员
// __proto__这个魔法属性在这些浏览器不能工作: ie 6/7/8, safari < 5, opera < 10.50
//当在cat的某个实例上检索一个属性时,如果在其本身中没有找到,则会延着原型链向上检索,如下例子中的c.__proto__即为一个animal对象
//如果检索c.breathes,如果在c对象本身没有找到此属性,则会检索t.__proto__.breathes、t.__proto__.__proto__.breathes等原型链上的对象,直到找到为止,没找到返回undefined
cat.prototype = new animal("live");
//cat继承的原型对象是具有特定状态的animal对象
var c = new cat();
console.log(cat.prototype);
console.log(cat.prototype.constructor.tostring());
console.log(c.constructor.tostring());
console.log("cat breathes:" + c.breathes);
console.log("c.__proto__:", c.__proto__);
//ie不支持此属性
//你可以利用object.__proto__这个魔法属性修改当前对象的原型,下面将一只猫猫化为人形
var d = new cat();
d.__proto__ = new human();
console.log("d.__proto__:", d.__proto__);
//从上面结果可以看到cat的实例c.constructor不是指向cat这个构造函数,而是animal构造函数
//需要修改对象的constructor为其构造函数本身
//当一个函数对象被创建时,function构造器产生的函数对象会运行类似这样的一些代码:this.prototype = {constructor: this},参考javascript: the good parts 5.1节说明
//新函数对象被赋予一个prototype属性,其值是包含一个constuctor属性,并且其属性值为此新函数对象本身
//但是通过原型方式继承时,会给prototype重新赋予一个新对象,此prototype对象中的constructor是指向其自身的构造函数,而不是新函数的,所以需要重置其fn.prototype.constructor = this
//参考javascript权威指南第五版example 9-3. subclassing a javascript class
cat.prototype.constructor = cat;
console.log(cat.prototype.constructor.tostring());
console.log(c.constructor.tostring());
console.log(c.__proto__);
var tostring = object.prototype.tostring;
language = function() {
this.type = "programming";
return {
"locale": "en",
"class-free": function() {
return false
},
"tostring": function() {
return tostring.apply(this, arguments)
}
// 如果tostring方法被重写成非function对象,则后面console中无法输出对象j
}
},
javascript = function() {
this.value = "javascript";
this["class-free"] = function() {
return true
};
};
language.prototype = {
a: 1,
b: 2
};
javascript.prototype = new language();
var j = new javascript();
console.log(j);
console.log(j.__proto__);
//locale: en,此处因为language构造函数返回不是this,而是另一个object直接量,而object直接的构造方法为object(),因此language的原型被丢失了
console.log(language.prototype);
console.log(javascript.prototype);
console.log(j.constructor.tostring());
//function object() { [native code] }


构造函数与其返回值


构造函数会返回一个对象,如果没有直接return语句,构造函数会自动返回当前对象:"return this;",也可以返回一个对象直接量,而不返回this,这样会中断正常的原型链。

prototype.js中class对象定义是封装在一个匿名函数里的,从而使得其内部变量和方法与外界隔离,其中有二句代码为:

function subclass() {};
subclass.prototype = parent.prototype;

因为parent的构造可能返回语句不是返回this对象,而是返回了一个其他的对象,如{tostring:true},如果不用subclass.prototype=parent.prototype这样写,可能这样会丢失原型链上的方法和属性,通过subclass这个空构造将parent.prototype引用到自身的prototype上,从而保持住部分原型链。
这其实也已经不是原型继承了,因为它不是通过new parent()来获取原型对象,丢失了new parent所得对象中的属性和方法。
prototype中的class其实放弃了原型对象,只是简单的继承了parent.prototype对象,已经失去原型继承可以继承对象状态的功能,这样操作其实是很好的模似了类继承方式。

var class = (function() {
function subclass() {};
function create() {
var parent = null,
properties = $a(arguments);
if (object.isfunction(properties[0])) parent = properties.shift();

function klass() {
this.initialize.apply(this, arguments);
}

object.extend(klass, class.methods);
klass.superclass = parent;
klass.subclasses = [];

if (parent) {
// 因为parent的构造可能返回对象直接量,而不是返回this,如{tostring:true}
subclass.prototype = parent.prototype;
klass.prototype = new subclass;
parent.subclasses.push(klass);
}

for (var i = 0; i < properties.length; i++) klass.addmethods(properties[i]);
if (!klass.prototype.initialize) klass.prototype.initialize = prototype.emptyfunction;
klass.prototype.constructor = klass;
return klass;
}
function addmethods(source) {
var ancestor = this.superclass && this.superclass.prototype;
var properties = object.keys(source);
if (!object.keys({
tostring: true
}).length) {
if (source.tostring != object.prototype.tostring) properties.push("tostring");
if (source.valueof != object.prototype.valueof) properties.push("valueof");
}
for (var i = 0, length = properties.length; i < length; i++) {
var property = properties[i],
value = source[property];
if (ancestor && object.isfunction(value) && value.argumentnames().first() == "$super") {
var method = value;
value = (function(m) {
return function() {
return ancestor[m].apply(this, arguments);
};
})(property).wrap(method);
value.valueof = method.valueof.bind(method);
value.tostring = method.tostring.bind(method);
}
this.prototype[property] = value;
}
return this;
}
return {
create: create,
methods: {
addmethods: addmethods
}
};
})();

Thursday, December 03, 2009

mysql5中注意UUID函数的使用

NOW() 函数,因为在二进制日志里已经包括了时间戳,可以被正确复制到slave server上。
UUID() 函数,具有非确定性,所以不能被复制到slave server,所以在存储过程或者触发器中要慎用。
the UUID() function is nondeterministic (and does not replicate). You should be careful about using such functions in triggers. It is not safe.
SYSDATE() 函数也具有非确定性,与NOW()函数不一样,在同步复制时会与master上的时间不一致。官方文档说明如下:
SYSDATE()
Returns the current date and time as a value in 'YYYY-MM-DD HH:MM:SS' or YYYYMMDDHHMMSS.uuuuuu format, depending on whether the function is used in a string or numeric context.

As of MySQL 5.0.13, SYSDATE() returns the time at which it executes. This differs from the behavior for NOW(), which returns a constant time that indicates the time at which the statement began to execute. (Within a stored routine or trigger, NOW() returns the time at which the routine or triggering statement began to execute.)


mysql> SELECT NOW(), SLEEP(2), NOW();
+---------------------+----------+---------------------+
| NOW() | SLEEP(2) | NOW() |
+---------------------+----------+---------------------+
| 2006-04-12 13:47:36 | 0 | 2006-04-12 13:47:36 |
+---------------------+----------+---------------------+

mysql> SELECT SYSDATE(), SLEEP(2), SYSDATE();
+---------------------+----------+---------------------+
| SYSDATE() | SLEEP(2) | SYSDATE() |
+---------------------+----------+---------------------+
| 2006-04-12 13:47:44 | 0 | 2006-04-12 13:47:46 |
+---------------------+----------+---------------------+

In addition, the SET TIMESTAMP statement affects the value returned by NOW() but not by SYSDATE(). This means that timestamp settings in the binary log have no effect on invocations of SYSDATE().

Because SYSDATE() can return different values even within the same statement, and is not affected by SET TIMESTAMP, it is non-deterministic and therefore unsafe for replication. If that is a problem, you can start the server with the --sysdate-is-now option to cause SYSDATE() to be an alias for NOW(). The non-deterministic nature of SYSDATE() also means that indexes cannot be used for evaluating expressions that refer to it.

Thursday, May 14, 2009

RegExp escape function

RegExp.escape = (function() {
var punctuationChars = /([.*+?|/(){}[\]\\])/g;
return function(text) {
return text.replace(punctuationChars, '\\$1');
}
})();

var str = RegExp.escape('a+b/c*d$ ^{.}');
var reg = new RegExp(str);


Reference: http://simonwillison.net/2006/Jan/20/escape

Saturday, January 03, 2009

trap of in_array in php

$array = array('testing',0,'name');
var_dump($array);
//this will return true
var_dump(in_array('foo', $array));
//this will return false
var_dump(in_array('foo', $array, TRUE));

Reference:
http://cn.php.net/manual/en/function.in-array.php

Monday, December 08, 2008

usage of call_user_func_array function in php


<?php

class Foo {
static public function test($name) {
print "Hello {$name}!\n";
}

public function bar($name){
print "Hello {$name}\n";
}
}

// call static Class methods.
call_user_func_array('Foo::test', array('Hannes'));
// Hello Hannes!
call_user_func_array(array('Foo', 'test'), array('Philip'));
// Hello Philip!


$foo = new Foo();
// call object instance methods.
call_user_func_array(array($foo, 'bar'), array('World!'));
call_user_func_array(array($foo, 'bar'), 'World!');
// Hello World!

?>

参考php手册:
callback
有些诸如 call_user_function() 或 usort() 的函数接受用户自定义的函数作为一个参数。Callback 函数不仅可以是一个简单的函数,它还可以是一个对象的方法,包括静态类的方法。
一个 PHP 函数用函数名字符串来传递。可以传递任何内置的或者用户自定义的函数,除了 array(),echo(),empty(),eval(),exit(),isset(),list(),print() 和 unset()。
一个对象的方法以数组的形式来传递,数组的下标 0 指明对象名,下标 1 指明方法名。
对于没有实例化为对象的静态类,要传递其方法,将数组 0 下标指明的对象名换成该类的名称即可。
Reference:
http://cn.php.net/manual/en/function.call-user-func-array.php

Sunday, October 05, 2008

Extending javascript Function prototype object

Function.prototype.twice = function() {
var fn = this;
return function() {
return fn.call(null, fn.apply(null, arguments));
};
};

Function.prototype.twice2 = function() {
var fn = this;
return function() {
console.log(this); // Window Object
return fn.call(this, fn.apply(this, arguments));
};
};

function plus1(x) { return x + 1; }
var plus2 = plus1.twice();
var plus3 = plus1.twice2();
console.log(plus2(10)); // 12
console.log(plus3(10)); // 12
Reference:http://osteele.com/talks/ajaxian-2008/samples/idioms-9.js.html

Friday, October 03, 2008

Diefference between "function func(){}" and "var func = function(){}" in javascript


console.log(f); // undefined
console.log(h()); // true

// This line of code defines an unnamed function and stores a reference to it
// in the variable f. It does not store a reference to the function into a variable
// named fact, but it does allow the body of the function to refer to itself using
// that name.
var f = function fact(x) { if (x <= 1) return 1; else return x * fact(x - 1); };
try {
console.log(f);
console.log(fact);
} catch (e) {
console.error(e.message)
}
console.log(f(1));
console.log(f(2));
console.log(f(3));
var g = function (x) {if (x <= 1) return 1; else return x * arguments.callee(x - 1);};
console.log(g(4));
function h() {return true}

其中需要说明一下"var func = function(){}" 与 "function func(){}"这二者的区别是后者用function语句定义的variable会先于此function运行前被初始化,因此h()函数调用可以写在其定义语句之前,而前者用var声明的variable则只能在此变量声明之后才可以被调用,与其他用var声明的变量完全一样。
另"var f = function fact(x) { if (x <= 1) return 1; else return x * fact(x - 1); };"这个写法要注意是在javascript1.5版本之后才被实现。

JavaScript函数调用时的作用域链和调用对象是如何形成的及与闭包的关系

1、javascript解析器启动时就会初始化建立一个全局对象global object,这个全局对象就拥有了一些预定义的全局变量和全局方法,如Infinity, parseInt, Math,所有程序中定义的全局变量都是这个全局对象的属性。在客户端javascript中,Window就是这个javascript的全局对象
2、当javascript调用一个function时,会生成一个对象,称之为call object(调用对象),function中的局部变量和function的参数都成为这个call object的属性,以免覆写同名的全局变量。
调用对象: ECMAScript规范术语称之为activation object(活动对象)。
3、javascript解析器每次执行function时,都会为此function创建一个execution context执行环境,在此function执行环境中最重要的一点就是function的作用域链scope chain,这是一个对象链,由全局对象调用对象构成,对象链具体构成过程见下面说明。
4、当javascript查询变量x的值时,就会检查此作用域链中第一个对象,可能是调用对象或者是全局对象,如果对象中有定义此x属性,则返回值,不然检查作用域链中的下一个对象是否定义x属性,在作用域链中没有找到,最后返回undefined。
5、当javascript调用一个function时,它会先将此function定义时的作用域作为其作用域链,然后创建一个调用对象,置于作用域链的顶部,function的参数及内部var声明的所有局部变量都会成为此调用对象的属性。
6、this关键词指向方法的调用者,而不是以调用对象的属性存在,同一个方法中的this在不同的function调用中,可能指向不同的对象。
7、The Call Object as a Namespace
(function() {
// 在方法体内用var声明的所有局部变量,都是以方法调用时创建的调用对象的属性形式存在。
// 这样就避免与全局变量发生命名冲突。
})();
8、javascript中所有的function都是一个闭包,但只有当一个嵌套函数被导出到它所定义的作用域外时,这种闭包才强大。如果理解了闭包,就会理解function调用时的作用域链和调用对象,才能真正掌握javascript。
9、当一个嵌套函数的引用被保存到一个全局变量或者另外一个对象的属性时,在这种情况下,此嵌套函数有一个外部引用,并且在其外围调用函数的调用对象中有一个属性指向此嵌套函数。因为有其他对象引用此嵌套函数,所以在外围函数被调用一次后,其创建的调用对象会继续存在,并不会被垃圾回收器回收,其函数参数和局部变量都会在这个调用对象中得以维持,javascript代码任何形式都不能直接访问此对象,但是此调用对象是嵌套函数被调用时创建的作用域链中的一部分,可以被嵌套函数访问并修改。

Wednesday, October 01, 2008

jQuery core function examples


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript" charset="utf-8" src="/lib/jquery/jquery-1.2.6.js"></script>
<style type="text/css" media="screen">
.first {
color: #f90;
}
.second {
color: #f00;
min-height: 20px;
border: #949 1px solid;
margin: 5px 0px;
}
.three {
float:right;
}
</style>
</head>
<body>
<div>Click here</div>
<div>to iterate through</div>
<div>these divs.</div>

<div id="d1">div#d1</div>
<div class="first">div.first</div>
<div class="first">div.first</div>
<div class="first">div.first</div>
<p>one</p> <div><p>two</p></div> <p>three</p>
To do list: <span class="three">(click here to change)</span>
<ul>
<li>Eat</li>
<li>Sleep</li>

<li>Be merry</li>
</ul>
<button>Change colors</button>
<span>this span innerText will be changed.</span>
<div class="second"></div>
<div class="second"></div>
<div class="second"></div>
<div class="second"></div>
<div class="second"></div>
<div class="second" id="stop">Stop here</div>
<div class="second"></div>
<div class="second"></div>
<div class="second"></div>
<div class="second"></div>

<input type="checkbox" name="t1" value="test1" id="t1"/>

<script type="text/javascript" charset="utf-8">
$("<div><p>Hello</p></div>").appendTo("body");
// Does NOT work in IE:
// $("<input/>").attr("type", "checkbox").appendTo("body");
// Does work in IE:
$("<input type='checkbox'/>").appendTo("div.first");
$("<input type='checkbox'/>").insertBefore("#d1");
$(".first").hide();
$(function () {
console.log("document ready");
});
$("div > p").css("border", "1px solid gray");
$('input:checkbox').get(0).checked = true;
$(document.body).click(function () {
$("div").each(function (i) {
console.log(i);
if (i == 2) return true; // skip this step
if (i == 5) return false; // break loop
if (this.style.color != "blue") {
this.style.color = "blue";
} else {
this.style.color = "";
}
});
});
$("span.three").click(function () {
$("li").each(function(){
$(this).toggleClass("first");
});
});
$("button").click(function () {
$("div.second").each(function (index, domEle) {
// this == domEle, $(this) == jQuery Object
$(domEle).css("backgroundColor", "yellow");
if ($(this).is("#stop")) {
$("span").not(".three").text("Stopped at div index #" + index);
return false; // break loop
}
});
});
</script>
</body>
</html>

Wednesday, May 07, 2008

test scope of this in closure and in anonymous functions

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>test scope of this in closure and in anonymous functions</title>
<script type="text/javascript">
var foo = 'this is window.foo!';
var d = [1, 2, 3];
// timeout functions
function Constructor() {
this.foo = 'this is Constructor.foo!';
var that = this;
this.timerId = window.setTimeout(function() {
// alert(this); // will get [object Window]
alert("this.foo = " + this.foo);
alert("that.foo = " + that.foo);
} , 1000);
}
// local functions
Constructor.prototype.getFoo = function() {
alert(this); // [object Object]
var getExternalFoo = (function() {
// alert(this); // will get [object Window]
return d.concat(this.foo)
})();
return getExternalFoo;
};
// using Function.call(object)
Constructor.prototype.getBar = function() {
var getInternalFoo = (function() {
// alert(this); // will get [object Object]
return d.concat(this.foo)
}).call(this);
return getInternalFoo;
};
var f = new Constructor();
document.write(f.getFoo());
document.write("<br />");
document.write(f.getBar());

</script>
</head>
<body>
</body>
</html>

在window.setTimeout和全局环境中的匿名方法中的this是指向window对象的,所以在调用过程中可以将此匿名方法做为实际的某个对象(如this对象)的方法来调用.

Friday, March 21, 2008

difference of function toString() in IE7 and FF2

IE7:
alert(/x/.test(function(){'x';}))
// => true
(function(){'x';}).toString();
// => "(function(){'x';})"

FF2:
alert(/x/.test(function(){'x';}))
// => false
(function(){'x';}).toString();
// => "function () { }"

Wednesday, February 20, 2008

Javascript function results caching

<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>javascript function results caching</title>
<script type="text/javascript">
var overrideSelf = function () {
return overrideSelf = 'test';
};
alert(overrideSelf);
alert(overrideSelf());
// alert(overrideSelf()); // overrideSelf is not a function
alert(overrideSelf);

var fnl = function () {
var v = 'xxx';
alert('alert from fnl');
return (fnl = function () {
return v;
})();
};
alert(fnl());
alert(fnl());
alert(fnl());

var fnp = function () {
if(!fnp.b) {
fnp.v = 'yyy';
alert('alert from fnp');
fnp.b = true;
}
return fnp.v;
};
alert(fnp());
alert(fnp());
alert(fnp());

var fnm = (function () {
var v, b = false;
return function () {
if (!b) {
v = 'zzz';
alert('alert from fnm');
b = true;
}
return v
}
})();
alert(fnm());
alert(fnm());
alert(fnm());
</script>
</head>

<body>
test function results caching
</body>
</html>
references:
http://developer.yahoo.net/blogs/theater/archives/2007/12/high_performance_ajax_applications.html

Friday, February 15, 2008

Translate selection text to chinese in new window

Firefox:
javascript:var dict=function(){var select=document.getSelection();var url='http://sh.dict.cn/search/?q='+select;window.open(url);return ;};dict();

闭包(closures)的写法:(function(){var q=String(window.getSelection());var url='http://sh.dict.cn/search/?q='+q;window.open(url);return;})();

IE7:
javascript:var dict=function(){var select=document.selection.createRange().text;var url='http://sh.dict.cn/search/?q='+select;window.open(url);return ;};dict();

上面function里最后面必须是return; (相当于是return undefined;)否则当前页面会被function return的结果重写,要防止结果重写,也可以将dict()方法调用包含到void操作符内:
void((function(){var q=String(window.getSelection());var url='http://sh.dict.cn/search/?q='+q;window.open(url);return false;})());
usage:
1. 新建一个书签,目标URL用上面的代码,IE会有个提醒,需要确认一下。
2. 在打开的网页里,如GOOGLE READER,要查某个词,选中此词。
3. 点击刚新建的书签(bookmarklet),IE会再次提醒。

Tuesday, February 12, 2008

Using parseFloat() or "+" instead of parseInt()

parseInt() 在解析字符串为数字的时候,有时候会有点问题,如
parseInt("010") 可以被解析成10,也可能被解析成8,字符串以"0"开头可以被做为8进制解析也可以被做为十进制解析,所以parseInt('08')得到的结果是0,而parseInt('07')得到的结果却是7,如果parseInt('08', 10)的第二个参数明确说明解析为十进制数字时就会得到结果8。
一般解析字符串为数字时可以用parseFloat()这个全局函数或者是"+"运算符。
['2008', '02', '11', '06', '21', '03'].map(function(v) { return + v });
# [2008, 2, 11, 6, 21, 3]

Sunday, January 27, 2008

方法名做为另外一个函数的参数-闭包用法一

<html>
<head><title> test cloures </title></head>
<body>
<script type="text/javascript" charset="utf-8">
var a = b = 1; // var a = (b = 1), variable b is no declared(like var b, the scope of b is global.)
function test() {
alert("a=" + a); // 1
alert("b=" + b); // 10
return a + b;
}

function testClosures(funcName) {
var a = b = 10; // var a = (b = 10); b is a global variable.
return funcName();
}
alert(testClosures(test));
</script>
</body>
</html>

javascript中相同命名空间下函数名和变量名冲突


<script type="text/javascript" charset="utf-8">
function test() {
alert(arguments.callee);
}
var test = 'xyz';
alert(test); // 'xyz'
test(); //test is not a function [Break on this error] test();
</script>

函数名其实也是一个变量名,所以是会发生冲突的。

Monday, January 21, 2008

Javascript function and anonymous function differrence 1

Javascript函数存在于定义它们的整个作用域(包括出现在该函数语句前面的语句)内。与之相反, Javascript匿名函数只是为后续的语句定义的。如下example:


<html>
<head>
<title> test stateFunction and expressionFunction difference</title>
</head>
<body>
<div id="d1">d1</div>
<div id="d2">d2</div>
doc_write is not a function<br />
[Break on this error] doc_write(document.getElementById('d1').innerHTML);
<script type="text/javascript" charset="utf-8">
doc(document.getElementById('d1').innerHTML);
doc_write(document.getElementById('d1').innerHTML);

function doc(argument) {
document.write("<p>\n");
document.write(argument);
document.write("</p>\n");
}

var doc_write = function(args) {
document.write("<p>\n");
document.write(args);
document.write("</p>\n");
};
</script>
</body>
</html>

Monday, October 15, 2007

JavaScript中的闭包closures简单说明

<script type="text/javascript">
uniqueID = (function() { // The call object of this function holds our value
var id = 0; // This is the private persistent value
// The outer function returns a nested function that has access
// to the persistent value. It is this nested function we're storing
// in the variable uniqueID above.
return function() { return id++; }; // Return and increment
})(); // Invoke the outer function after defining it, and return a function: function() { return id++; }

alert(uniqueID()); // alert(function() { return id++; }());
alert(uniqueID());
alert(uniqueID());
// JavaScript函数是将要执行的代码以及执行这些代码的作用域和作用域的arguments一起构成的一个综合体,即使函数包含相同的JavaScript代码,并且每段代码都是从相同的作用域调用的,还是可以返回不同的结果的。因为JavaScript中的函数是在当时定义它们的作用域里运行的,而不是在执行它们的作用域里运行的。这种代码和作用域的综合体叫闭包。所有的JavaScript函数都是闭包。
</script>

当一个嵌套函数被导出到它所定义的作用域外时,这种闭包才有意思。当一个嵌套的函数以这种方式使用时,通常被明确的叫做一个闭包。
uniqueID的函数体为function() { return id++; },它是从一个function literal中返回得到,并包含了导出后的作用域,包含了变量名和值等,也就是从这个匿名函数是返回了一个闭包。
在uniqueID被函数运算符()调用时,已经在函数定义的作用域外,所有调用操作会影响闭包内的变量并仍会被此闭包继续保存。

Ruby和Perl中有个lambda方法也可以生成一个闭包。

更多关于javascript的闭包说明请查看此处

Function() constructor of JavaScript

There are a few points that are important to understand about the Function() constructor:

The Function() constructor allows JavaScript code to be dynamically created and compiled at runtime. It is like the global eval() function (see Part III) in this way.

The Function() constructor parses the function body and creates a new function object each time it is called. If the call to the constructor appears within a loop or within a frequently called function, this process can be inefficient. By contrast, a function literal or nested function that appears within a loop or function is not recompiled each time it is encountered. Nor is a different function object created each time a function literal is encountered. (Although, as noted earlier, a new closure may be required to capture differences in the lexical scope in which the function is defined.)

A last, very important point about the Function() constructor is that the functions it creates do not use lexical scoping; instead, they are always compiled as if they were top-level functions, as the following code demonstrates:


var y = "global";
function constructFunction() {
var y = "local";
return new Function("return y"); // Does not capture the local scope!
}

// This line displays "global" because the function returned by the
// Function() constructor does not use the local scope. Had a function
// literal been used instead, this line would have displayed "local".
alert(constructFunction()()); // Displays "global"

JavaScript中函数function说明

从技术上说,function并非是一个语句。在JavaScript程序中,语名会引发动态的行为,但是函数定义描述的却是静态的程序结构。语句是在运行时执行的,而函数是在实际运行之前,浏览器载入JavaScript的时候被解析的,或者说是在被编译时定义了这个函数。当Javascript解析程序遇到一个函数定义时,它就解析并存储(而不执行)构成函数主体的语句,然后定义一个和该函数同名的属性(如果函数定义嵌套在其他函数中,那么就在调用对象中定义这个属性,否则在全局对象中定义这个属性)以保存它。
The fact that function definitions occur at parse time rather than at runtime causes some surprising effects. Consider the following code:
<script type="text/javascript">
alert(f(4)); // Displays 16. f( ) can be called before it is defined.
var f = 0; // This statement overwrites the property f.
function f(x) { // This "statement" defines the function f before either
return x*x; // of the lines above are executed.
}
alert(f); // Displays 0. f( ) has been overwritten by the variable f.
</script>
另外如果Ajax调用返回的内容包含JS的话,需要对JS进行eval()操作,才能获取到JS中的变量和方法,其中方法必须以Function Literals直接量的方式赋个一个变量才能获得此方法。另外Ajax载入的JS中变量都要以全局变量方式载入才能得到,即变量前不能加var声明。
Function内部语句发变量定义如果不加var声明的话,只要function被执行过,此变量也会成为一个全局变量。