js function生成的方法
来源:互联网 发布:域名注册多少钱 编辑:程序博客网 时间:2024/06/11 23:42
参考来源:http://blog.csdn.net/corchen/article/details/7735670
函数是JavaScript中很重要的一个语言元素,提供了一个function关键字和内置对象Function,下面是其可能的用法和它们之间的关系。
使用方法一:
var foo01 = function() //or fun01 = function()
{
var temp = 100;
this.temp = 200;
return temp + this.temp;
}
alert(typeof(foo01));
alert(foo01());
{
var temp = 100;
this.temp = 200;
return temp + this.temp;
}
alert(typeof(foo01));
alert(foo01());
运行结果:
function
300
最普通的function使用方式,定一个JavaScript函数。两种写法表现出来的运行效果完全相同,唯一的却别是后一种写法有较高的初始化优先级。在大扩号内的变量作用域中,this指代foo01的所有者,即window对象。
使用方法二:
var foo02 = new function()
{
var temp = 100;
this.temp = 200;
return temp + this.temp;
}
alert(typeof(foo02));
alert(foo02.constructor());
{
var temp = 100;
this.temp = 200;
return temp + this.temp;
}
alert(typeof(foo02));
alert(foo02.constructor());
运行结果:
object
300
这是一个比较puzzle的function的使用方式,好像是定一个函数。但是实际上这是定一个JavaScript中的用户自定义对象,不过这里是个匿名类。这个用法和函数本身的使用基本没有任何关系,在大扩号中会构建一个变量作用域,this指代这个作用域本身。
使用方法三:
var foo3 = new Function(’var temp = 100; this.temp = 200; return temp + this.temp;’);
alert(typeof(foo3));
alert(foo3());
alert(typeof(foo3));
alert(foo3());
运行结果:
function
300
使用系统内置函数对象来构建一个函数,这和方法一中的第一种方式在效果和初始化优先级上都完全相同,就是函数体以字符串形式给出。
使用方法四:
var foo4 = Function(’var temp = 100; this.temp = 200; return temp + this.temp;’);
alert(typeof(foo4));
alert(foo4());
alert(typeof(foo4));
alert(foo4());
运行结果:
function
300
这个方式是不常使用的,效果和方法三一样,不过不清楚不用new来生成有没有什么副作用,这也体现了JavaScript一个最大的特性:灵活!能省就省。
- js function生成的方法
- Function:--js中创建函数的方法
- js中三种使用function()的方法
- js function定义函数的方法
- js生成uuid的方法
- js生成uuid的方法
- JS生成 UUID的方法
- function 方法解决js问题
- js中Function有用的属性和方法
- js function定义函数的几种方法
- js function定义函数的几种方法
- JS获取function方法里定义的对象
- js中Function.prototype的bind()方法-学习笔记
- js怎么调用 var a=function (){ }()里面的方法
- js生成随机数的方法实例总结
- JS生成 UUID的四种方法
- JS生成 UUID的四种方法
- JS生成 UUID的四种方法
- is-a与has-a的关系
- JAVA NIO 简介
- Unix常用命令
- 使用flowplayer给网站添加视频播放功能
- C语言学习日记—— C Programming language second edition
- js function生成的方法
- [Java] Thread-02 sleep-join-yield 图文 对应上一篇文章
- LeetCode Rotate Image旋转图像
- 【译】用Arduino制作爱情指示计
- js中call与apply用法
- 数据结构c语言实现之单链表
- Jquery+jsonp+ajax跨域访问
- Alarm
- /proc/pid下的相应信息说明