Javascript - 函数分类 & this指向

JS中定义函数的三种方式

通过实例来说明吧

<script>
        //method1
        function fn() {
            console.log('fn created ');
        }
        //method2
        var fn2 = function () {
            console.log('fn2 created');
        }
        //method3
        var fn3 = new Function('test', 'console.log(test);');
        fn3('fn3 test');
        console.dir(fn3);
        console.log(fn3 instanceof Object);
    </script>

运行上面例子,证明了函数也是对象。可以采用new + 构造函数的方式创建实例,第三种方式执行效率低。

函数的原型链

在这里插入图片描述

从结果可以看到Function原型对象的__proto__指向Object。
在这里插入图片描述

JS中函数的分类和调用方式

通过实例来说明吧

<script>
        //函数的分类和调用方式
        //方式1 普通标准函数,this 指向window
        function fn() {
            console.log('fn1'+ this);
        }
        fn(); //本质是window.fn(); 全局函数是window的成员       
        //方式2 对象的方法 this 指向调用者o
        var o = {
            sayHi: function () {
                console.log('fn2'+this);
            }
        }
        o.sayHi();

        //方式3 构造函数 this指向新创建的对象,这里指向star1
        function Star(username){
            this.username = username;
        }
        var star1 = new Star('ldh');

        //方式4 绑定事件函数 this 指向函数的调用者 btn
        var fn = function (){
            console.log('btn 被点击了'+ this);
        }
        btn.onclick = fn;
        //点击了按钮就可以调用函数

        //方式5 定时器函数 定时器实际是window成员 所以this 就是window
        setInterval(function(){},1000);
        //定时器按照设定的时间间隔去调用
        
        //方式6 立即执行函数 this 是window 同方式一
        (function(){console.log('function executed')})();
		//不需要调用立即执行   
		
		//方式7 箭头函数(lambda 表达式)this 指向obj
        var obj = { name: 'test' };
        function fn() {
            console.log(this);
            return () => console.log(this);
        }
        const fnTest = fn.call(obj);
        fnTest();
    </script>

通过上面的例子,基本上归纳了笔者了解的函数使用方式。通过方式4和方式6的对比,

  • 我们可以知道函数后面加了() 表示立即调用,没加(),表示函数的指针,只是指明函数不调用函数。
  • this 指向问题,牢记this指向调用者
  • 方式7 的箭头函数 在后端语言中非常常见,称为lambda 表达式是一种语法糖
  • JS中箭头函数不绑定this,如果在箭头函数中使用this,this指向箭头函数定义位置处的this。JS解析箭头函数时,内部使用bind方法改变this

箭头函数理解案例

var age = 0;
        var obj = {
            age: 100,
            say: () => { console.log(this.age); }
        }
        obj.say();//打印的结果时0 而不是100 .因为obj是全局变量,变成了window成员。而对象内部没有作用域,因此定义处的this指向window而不是obj,window.age =0

函数的参数

ES6之前,我们通过arguments伪数组来获得。但是在箭头函数中不能使用arguments对象,我们使用剩余参数(…args)的方式来获得。args是一个数组,使用更灵活
案例

<script>
        function fn() {
            console.log(arguments);
        };
        fn(1, 2, 3, 4, 5);
        fn();
//箭头函数 lambda
        const sum = (...args) => {
        console.log(args);
            let total = 0;
            args.forEach(element => {
                total += element;
            });
            return total;
        };
        console.log(sum(12, 432, 2123));
        
    </script>

改变this 指向的三个函数

this 指向是JS中很重要的问题,在上面的函数分类中,已经有了系统的分析。下面重点总结改变this 指向的三个函数

call

把父类实例改成子类实例 实现属性继承

<script>
        //call function 
        function Father(username, age) {
            this.username = username;
            this.age = age;
        }

        function Son(username, age, gender) {
            Father.call(this, username, age);//实现继承父类的属性
            this.gender = gender;
        }
    </script>

apply

apply 和call 不同点,参数是数组(或者伪数组)。在apply内部会把数组拆成元素
主要使用 借助Math对象,Math.max.apply(Math, [4324, 45, 342, 23])

<script>
        //apply function 
        var o = {
            username: 'testuser'
        };
        function fn(arr) {
            console.log(arr);
            for (let i = 0; i < arr.length; i++) {
                console.log(arr[i]);

            }
            console.log(this);
        }

        fn.apply(o, [23, 43]);
        console.log(Math.max(43, 45, 243, 342));
        console.log(Math.max.apply(Math, [4324, 45, 342, 23])); 
    </script>

bind

只改变this 的指向 不调用函数
用途改变绑定事件的this,案例

<body>
    <button>click me</button>
    <button>click me</button>
    <button>click me</button>
    <script>
        //bind function
        //案例:实现多个按钮发送验证码后 3s 可以再次发送
        var btns = document.querySelectorAll('button');
        for (let i = 0; i < btns.length; i++) {
            btns[i].onclick = function () {
                this.disabled = true;
                setTimeout(function () {
                    this.disabled = false;//改变this 指向btn ,3000ms 后执行
                }.bind(this), 3000);
            }
        }        
    </script>
</body>
评论 19
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值