让大家更加深刻的理解js相关语法
写原生js 代码就应该这么写,才是比较优雅的哦!
好好看一下下面代码
/ 这个是有名字的函数
function getInfo(){
console.log('你好哈,建伟')
}
// 这个是匿名函数: 就是去掉 getInfo
function (){
console.log('你好哈,建伟')
}
//但是你会发现:语法错误, 这样写不符合语法的啊
// 咋办呢? 加一个括号
(
function (){
console.log('你好哈,建伟')
}
)
// 但是没执行。 以上代码不会输出一个: 你好哈,建伟
// 咋办呢? 改造成: ()()
(
function (){
console.log('你好哈,建伟')
}
)(); //输出: 你好哈,建伟
问题:匿名函数如何传值呢?
(
function (str){
console.log(str)
}
)('你好哈,建伟'); //输出: 你好哈,建伟
这个匿名函数有啥作用呢?
1、闭包:进行代码和变量的隔离
2、类的构建,这个才是他的主要用途哦; 在es5前很有用,我们可以按模块构建js;
3、创建一个函数变量;
例如:建立一个小狗狗
(function(scope){
// 建立一个dog 函数变量
// 将一个匿名函数,赋值给dog
var dog=function(){
return this
}
dog.prototype = {
getName:function(){
return 'myDog'
}
}
// 把这个dog 挂载到window 这个全局类中去
// 注意点: mydog 这个是window上我自己定义的一个对象,指向 dog 函数变量
scope.mydog=dog;
}))(window)
这样你就可以全局使用dog了
写一个例子,你可以自己拷贝运行试试看
<!Doctype html>
<html>
<head>
<title>js test-【ljw】</title>
<meta charset="utf-8">
</head>
<script>
(function(scope){
var dog=function(){
this.init('myDoc','red');
return this;
}
dog.prototype = {
// 初始化一个小狗
init:function(name,color){
this.name=name;
this.color=color;
},
// 获取小狗的名字
getName:function(){
console.log('run--dog:',this.name)
return this.name
}
}
// 把这个对象给到window全局对象中去
scope.dog=dog;
})(window)
// 输出一个对象信息 ,这里我注视掉了,你也可以放开他
var dog1=new dog()
dog1.init('myDog 1','bule');
dog1.getName();
function getDog(){
var dog2=new dog()
dog2.init('myDog 2','bule');
alert(dog2.getName());
}
</script>
<body>
<div onClick="getDog();"> 点击我一下,试试看什么效果,我是灵猫说技术 </div>
</body>
</html>