JS call、apply、bind

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>call、apply、bind</title>
</head>
<body>
    <script>

        // call apply bind
        // call是一个方法,是函数的方法
        function fun (){
            console.log(this.name);
        }

        let cat = {
            name: '喵喵',
        }

        let dog = {
            name: '旺财',
            sayName(){
                console.log('我是' + this.name);
            },
            eat(food1, food2){
                console.log('我喜欢吃', food1, food2);
            }
        }

        // call 可以调用函数,call可以改变函数中this指向
        fun.call(cat);
        dog.sayName.call(cat);

        // call
        dog.eat.call(cat, '鱼', '肉');

        // apply
        dog.eat.apply(cat, ['鱼', '肉']);

        // bind
        let newFun = dog.eat.bind(cat, '鱼', '肉');
        newFun();
    </script>
</body>
</html>

上一篇:web前端必做笔记之一:call,apply,bind基本语法


下一篇:java多态instanceof介绍