235 继承 之 call()

ES6之前并没有给我们提供 extends 继承。

我们可以通过构造函数 + 原型对象模拟实现继承,被称为组合继承。 【构造函数:集成属性,原型对象:集成方法。】


调用这个函数, 并且修改函数运行时的 this 指向: 
fun.call(thisArg, arg1, arg2, ...)

thisArg :当前调用函数 this 的指向对象
arg1,arg2:传递的其他参数
  • call():可以调用函数
  • call():可以修改this的指向, 使用call()的时候,参数一是修改后的this指向, 参数2, 参数3... 使用逗号隔开连接
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <script>
        // call 方法
        function fn(x, y) {
            console.log(x + y);  // 3
            console.log(this);  // {name: "andy"}
            console.log(this.name);  // andy
            console.log(this['name']);  // andy
        }
        var o = {
            name: 'andy'
        };
        // fn();
        // 1. call() 可以调用函数
        // fn.call();

        // 2. call() 可以改变这个函数的this指向 此时这个函数的this 就指向了o这个对象
        fn.call(o, 1, 2);
    </script>
</body>

</html>

posted on 2020-01-21 14:04  冲啊!  阅读(113)  评论(0编辑  收藏  举报

导航