Appearance
一、函数的声明
- 函数声明:
function fn(){} - 表达式声明:
var fn = function(){}
二、js中函数的调用
- test()
- obj.test()
- new test()
- test.call/apply(obj) 例:
js
var obj = {}
function test(){}
test.call(obj) // 通过对象调用函数三、回调函数
- dom点击事件回调
- 定时器回调函数
- ajax回调函数
- 声明周期回调函数
四、IIFE
全称:Immediately-Invoked Function Expression(立即执行函数表达式)
匿名函数自调用 写法:
js
(function (){
console.log(12323)
})()作用:隐藏实现,不会污染全局匿名空间,用来编写js模块
js
(function (){
var a = 1
function test(){
console.log(a)
}
window.$ = function (){//向外暴露一个全局函数
return {
test: test
}
}
})()
$().test();//调用执行,$是一个函数,$执行后返回的是一个对象五、函数中的this
- 任何函数都是通过某个对象进行调用,如果没有指定,就是window调用。
- 所有的函数内部都有一个变量叫this
- this的值是调用函数的当前对象
- 如何确定this的值?
- test():当前对象是window
- obj.test():obj
- new test():新创建的对象
- test.call/apply(obj):obj 示例:
js
function Person(color) {
console.log(this)
this.color = color
this.getColor = function () {
console.log(this)
return this.color
}
this.setColor = function (color) {
console.log(this)
this.color = color
}
}
Person('red') // this是window
var p = new Person('blue') // this是p
p.getColor() // this: p
var obj = {}
p.setColor.call(obj,'black') this:obj
var test = p.setColor;
test() // this:window
function fun1() {
function fun2() {
console.log(this)
}
fun2() // this:window
}
fun1()