//普通函数
function person2 (name,age) {
console.log(‘this:’,this)
this.name=name;
this.age=age;
my = ‘dhk’
this.sayName=function () {
console.log(this.name);
}
console.log(this.age);
}
var person = person2(“lucy”,“23”); //this 指向window
window.sayName(); //luck
//构造函数
function Person (name,age) { //一般都是首字母大写
this.name=name;
this.age=age;
this.sayName=function (){
console.log(this.name);
}
}
var personw =new Person("make","18"); //new 一个对象 this指向Person
personw.sayName(); //make
//匿名函数
(function(){
console.log("匿名函数自我调用");
})(); //调用匿名函数
// 将匿名函数赋值给变量
var cat = function () {
console.log("赋值的匿名函数");
}
cat();
//闭包
var mybox = (function box (n) {
return function(x){
return n+x;
}
})('测试')
console.log(mybox('dddd'));
//箭头函数
x => x * x; //相当于 function(x){return xx}
()=> 36;
(x,y)=>x*y;
//箭头函数闭包
var a = 10;
var foo = (a => (() => a++))(a);
foo()
箭头函数没有this,是继承上级的this
function f(){
this.a =1
return ()=> console.log(this.a)
}
f()() // 1
箭头函数没有arguments,是继承上级的arguments
function f(){
return ()=> console.log(arguments)
}
f(1,2)(3,4) // [1,2]
箭头函数没有prototype
箭头函数返回值
默认返回 const fun2 = ()=> 1+2; //return 3
如果是块语句必须写return, const fun2 = ()=> {return 1+2} //return 3
如果返回是对象,不想写return,可以用 ()包裹
const fun2 = ()=> ({a:2}) // return a:2
或者写全return
const fun2 = ()=> {return {a:2}} // return a:2