一、函数
这里不详细介绍函数,因为了解过其它语言,下面主要说的是JavaScript函数的独特之处
1.普通函数
function hello(num) {
return num+10;
}
2.对象属性函数
let hello = {
name: 15,
Whoyour: function (name) {
return name+'ok';
},
//简写
Noyour(value) {
this.name = value;
}
}
console.log(hello.name); // 15
console.log(hello.Whoyour('15551'))//15551ok
3.匿名函数
let hello = function(num) {
return num+20;
};
console.log(hello(15))// 35
4.箭头函数
解释:推荐在把函数用作参数时使用
例1
setTimeout(()=>{
console.log(123)
},1000)
例2
// 其中a和b都是参数
let doo= (a,b)=>{
console.log(a,b)
}
// 只有一个参数可以不加括号
let Hello = a=>{
console.log(a)
}
Hello(55)//55
doo(15,20)//15 20
二、this
关于this的指向问题
1.普通函数
解释:此时的this指向的winodw,在vue中此时this指向的是vue
let Hello = a=>{
console.log(this)
}
Hello()//Window {window: Window, self: Window, document: document, name: '', location: Location, …}
2.对象属性函数
let hello = {
a:55,
b:function(){
console.log(this)
}
}
hello.b()// {a: 55, b: ƒ}
3.箭头函数
解释:箭头函数没有this, 也可以理解为箭头函数中的this 会继承定义函数时的上下文,可以理解为和外层函数指向同一个 this
let hello = {
a:55,
b:()=>{ //使用箭头函数
console.log(this)
}
}
hello.b()//Window {window: Window, self: Window, document: document, name: '', location: Location, …}