JavaScript 箭头函数

1.写法对比

  • 传统函数
//传统函数
function sum(n1,n2){
    return n1+n2;
}
console.log(sum(1,2)); //3
  • 箭头函数
//求和
var sum = (n1,n2)=> {
    return (n1+n2)
}

//等价于
var sum = (n1,n2)=> n1 + n2;

console.log(sum(1,2)); //3

2.this指向

  • this存在于函数内部,谁调用他this就指向谁(绑定了this的函数除外),通俗的说,obj.fn(),this就指向obj
  • 直接调用:
//非严格模式下
function foo(){
    console.log(this); 
}
foo(); //全局环境下直接调用,相当于window.foo();,所以这里输出window

//严格模式下
function foo2(){
    "use strict"; // 这里是严格模式
    console.log(this); 
}
foo2(); // this = undefined
window.foo2(); // this = window
  • 对象调用:
// 对象中的this指向
var obj = {
    name: "张三",
    sayHello: function() {
        console.log("hello");
        console.log(this);
    }
}
obj.sayHello();  //this指向obj

// 多层嵌套的对象,内部方法的this指向离被调用函数最近的对象
// 本质上还是谁调用它this就指向谁
var obj = {
    name: "张三",
    func: {
        sayHello: function() {
            console.log("hello");
            console.log(this);
        }
    }
}
obj.func.sayHello();  // this指向obj.func
  • 引用调用:
// 引用调用
// 定义在最顶层的函数直接调用,this一律指向window
var obj = {
    name: "baidu",
    fn: function() {
        console.log(this)
    }
}
var test = obj.fn;
test(); // window
let test2 = obj.fn;
test2();  // window

var obj2 = {};
obj2.test = obj.fn;
obj2.test();  //obj2
  • 定时器中的函数:this指向window
  • HTML内联事件:
// 内联事件处理函数调用

<li onclick="console.log(this)">11111</li>
//指向li标签

<li onclick="show()">22222</li>

function show(){
    console.log(this);
}
// 指向window
  • 数组调用:数组其实也是一种特殊的对象,他的下标可以看成对象的key。对象可以使用obj.fn调用自己属性中的函数,此时this指向obj。而数组使用arr[0]可以看成是arr.0调用了第0个数组元素
//数组中函数的调用
var arr = [1,2,function(){console.log(this)}]
arr[2]()// [1, 2, ƒ]this指向数组本身
  • 箭头函数this指向:箭头函数自己没有this,无论谁已何种形式调用他,this都指向他的上层邻近函数的this,否则this指向window
// ES6对象中的this
var obj = {
    name: "张三",
    sayHello: () = >{
        console.log("hello");
        console.log(this);
    }
}
obj.sayHello(); // this指向window
// ES6嵌套对象中的this
var obj = {
    name: "张三",
    func: {
        sayHello: () =>{
            console.log("hello");
            console.log(this);
        }
    }
}
obj.func.sayHello(); // 指向window
// 引用调用
var obj = {
    name: "baidu",
    fn: () = >{
        console.log(this)
    }
}
var test = obj.fn;
test();  // 指向window
let test2 = obj.fn;
test2();  // 指向window

var obj2 = {};
obj2.test = obj.fn;
obj2.test();  // 指向window
// 事件处理函数调用
var li = document.getElementsByTagName('li');
li[0].onclick = () = >{
    console.log(this);  // window
    setTimeout(() = >{
        console.log(this);   // window
    },
    3000)
}
var li = document.getElementsByTagName('li');
li[0].onclick = function() {
    var x = 11;
    var obj = {
        x: 22,
        methods: {
            x: 33,
            say: function() {
                console.log(this.x)
            },
            say2: () = >{
                console.log(this)
            }
        }
    }

    obj.methods.say();  // 33
    obj.methods.say2();  // li标签
}
posted @ 2019-09-25 23:33  ---空白---  阅读(700)  评论(0编辑  收藏  举报