理解javascript函数

来源:互联网 发布:李娜 歌手 知乎 编辑:程序博客网 时间:2024/05/14 07:10

函数定义:命名函数(声明式),匿名函数(引用式)

function dwn(str) {document.write(str + "<br/>");}// 声明式,定义代码先于函数执行代码被解析function t1() {dwn("t1");}t1();function t1() {dwn("new t1");};t1();// 引用式,在函数运行中进行动态解析var t1 = function() {dwn("new new t1");};t1();var t1 = function() {dwn("new new new t1");};t1();// 以上输出:new t1,new t1,new new t1,new new new t1
        你可能会认为输出t1,new t1,new newt1,new new new t1,结果却并不是这样,应该理解这句话:声明式,定义代码先于函数执行代码被解析。如果深入一步,应该说是scope链问题,实际上前面两个方法等价于window.t1,可以理解为t1是window的一个公有属性,被赋了两次值,以最后一次赋值为最终值。

      当第四个方法改成function t1(){}这样的声明式时,结果变成了new new new t1,new new new t1,new new t1,new new t1,最后一个输出就难以理解了。

另外匿名函数还有(function(){...})()这样的写法,最后一个括号用于参数输入。
还有
var t1=new function(){..}这样的声明,实际上t1已经是一个对象了。

var t2 = new function() {var temp = 100; // 私有成员this.temp = 500; // 公有成员return temp + this.temp;};alert(typeof(t2)); // objectalert(t2.constructor()); // 600

使用系统内置函数对象来构建一个函数:
var obj = new Function('var temp = 100;this.temp = 200;return temp + this.temp;');alert(typeof(obj)); // functionalert(obj()); // 300
但是不建议上面的构建方式


原创粉丝点击