js_call\apply\bind的认识

辨别this的不同

        const person1 = {
            name: 'Nicholas',
            age: 74,
            job: 'engineer',
            getDetail: function () {
                console.log(`${this.name} is a ${this.job} and is ${this.age}`);
            }
        };
        const person2 = {
            name: 'Coco',
            age: 25,
            job: 'designer'
        };

        var name = "Mikey";
        // let 定义的变量是块级变量,let声明的全局变量,不会成为window的属性
        function show() {
            setTimeout(() => {
                console.log(this.name);
            }, 1000);
        }
        person1.getDetail(); // Nicholas is a engineer and is 74
        show(); // Mikey

关于let声明的变量在window里无法获取到的问题

关于let声明的变量在window里无法获取到的问题

call/apply/bind都是用来重定义this这个对象的

        person1.getDetail.call(person2); // Coco is a designer and is 25
        person1.getDetail.apply(person2); // Coco is a designer and is 25
        person1.getDetail.bind(person2)(); // Coco is a designer and is 25

bind返回的是一个重定义了this对象的函数,需要再次调用。

传参情况下三个方法的用法

        person1.getDetail.call(person2, 'Russia',
        'USA'); // Coco is a designer and is 25, come from Russia, and got to USA
        person1.getDetail.apply(person2, ['Russia',
        'USA']); // Coco is a designer and is 25, come from Russia, and got to USA
        person1.getDetail.bind(person2, 'Russia', 'USA')
        (); // Coco is a designer and is 25, come from Russia, and got to USA
        person1.getDetail.bind(person2, ['Russia', 'USA'])
        (); // Coco is a designer and is 25, come from Russia, and got to USA
  • call 方法通过单个字符串的方式接受参数,参数之间使用逗号间隔
  • apply 方法通过数组的方式接受参数
  • bind 方法两种方法都可以。注意再次调用返回的函数。
posted @ 2021-02-05 11:31  Syinho  阅读(76)  评论(0编辑  收藏  举报