函数
1、首先我们要知道什么是函数?
JavaScript 函数是被设计为执行特定任务的代码块。
JavaScript 函数会在某代码调用它时被执行。
2、什么是IIFE
立即执行函数 用于模块化的开发
函数自调用 最好在开头写上分号 代码块的编写更加友好
;(function fn(a){
console.log(this) //window
})(2)
//函数自调用 箭头函数
;((a,b)=>{
console.log(a+b)
})(3,2)
//函数自调用 箭头函数
;((a,b)=> console.log(a+b))(3,2)
; ((a, b) => {
let c = a+b
return c
})(3, 2)
// console.log(c) //c is not defined
; ((a, b) => {
window.$ = () => {
}
})(3, 2)
console.log(window.$()) //5
3、箭头函数
箭头函数怎么写
箭头函数如果参数只有一个 可以省略();如果返回值只有一句 {}也可以省略
格式 ()=>{}
对象
1、什么是对象
包含多个数据的容器,其中包含属性和方法
this
* 总结:调用方式不同,指向不同的对象(可以简单理解:基本上是谁调用,指向谁)
* 直接调用函数,函数中的this永远指向window对象
* 通过方法的形式调用函数,函数中的this指向调用方法的对象
* 通过构造函数的形式调用函数,函数中的this指向新创建的那个对象
* 使用call 和apply 可以改变this 的指向,this会指向新的对象
* 如果是DOM的事件函数,this 指向的是对应的事件
定义一个构造函数 Person
function Person(color) {
console.log("1", this) //window
this.color = color
this.getColor = function (color) {
console.log("2", this)
return this.color
}
this.setColor = function (color)
console.log("3", this)
this.color = color
}
}
Person('red'); //this 指向window 此时仅仅执行第一个console
// let p = new Person('red') //this 指向p,更严格应该指向Person,因为p指向Person 此时仅仅执行第一个console
// p.getColor() //this 指向p Preson
// let obj = {}
// p.setColor.call(obj, 'black') //this 指向obj
// // p先调用preson 的 setColor的方法,call方法将setColor方法的this指向到obj
// 同等于
// obj={
// setColor: color => {
// console.log("3", this)
// this.color = color
// }
// }
// let test = p.setColor;
// test(); //this 指向p Preson
//如果 用箭头函数 定义Person this 的指向是不一样的
function Person(color) {
console.log("1", this) //window
this.color = color
this.getColor = color => {
console.log("2", this)
return this.color
}
this.setColor = color => {
console.log("3", this)
this.color = color
}
}
// Person('red'); //this 指向window 此时仅仅执行第一个console
let p = new Person('red') //this 指向p,更严格应该指向Person,因为p指向Person 此时仅仅执行第一个console
// p.getColor() //this 指向p Preson
let obj = {}
p.setColor.call(obj, 'black') //this 指向 Preson
let test = p.setColor;
test(); //this 指向p Preson