arguments 原型对象 apply()和call()

29 阅读2分钟

arguments

arguments:是函数的内置对象
保存着所有实参的伪数组(不能调用数组相关API)
    function fun(){
        // console.log(arguments);
        for(let i=0; i<arguments.length; i++){
            console.log(arguments[i]);
        }
    }   
    fun(1,2,3,"heihei",true); 
​
设置不定参函数
    function fun(){
        for(let i=0; i<arguments.length; i++){
            if(typeof arguments[i] == "number"){
                console.log("执行数字相关操作");
            }else if(typeof arguments[i] == "string"){
                console.log("执行字符串相关操作");
            }else if(typeof arguments[i] == "boolean"){
                console.log("执行布尔相关操作");
            }
        }
    }
    fun(true,3);
​
arguments.callee:代表当前函数对象本身
在递归中可以使用callee属性代表函数对象本身,避免了外部改函数名,内部也需要改的问题
    function fun(){
        console.log(arguments.callee);//arguments.callee == fun
    }
​
    fun();

原型对象

原型对象:是函数对象(特指构造函数)的一个属性,prototype
函数对象.prototype 
作用:存储所有实例对象共享的方法和属性
​
类
    function Student(id,name){
        // 属性属于每个对象,应有独立的空间
        this.id = id;
        this.name = name;
        // 行为属于整个类族,只有一个,被所有该类的对象使用
        // this.eat = function(){
        //     console.log("eat");
        // }
        // this.sleep = function(){
        //     console.log("sleep");
        // }
    }
​
    Student.prototype.eat = function(){
        console.log(this.name + "eat");
    }
​
    Student.prototype.sleep = function(){
        console.log(this.name + "sleep");
    }
​
    Student.prototype.teacher = "大黄";
    Student.prototype.teacher = "嘻嘻";
​
类的实例化对象
    let s = new Student(1,"老王");
    let s1 = new Student(2,"小王王");
​
    s.eat();
    s1.eat();
​
    s.sleep();
    s1.sleep();
​
写:等价于在s对象上添加了一个新的teacher属性,覆盖了原型对象上的teacher
    s.teacher = "曹柏林";
​
    delete s.teacher;
​
    console.log(s.teacher,s1.teacher);
​
为什么实例化对象能访问所有的属性和方法?
原型图
实例对象创建时,会开辟属性空间,所有可以直接访问,
其次每个实例对象构造时的同时,还会创建一个_proto_属性,
该属性指向类的原型对象,所以实例对象遍可以访问原型对象上的属性和方法

apply()和call()

apply和call都是用来修改函数this指向的,他们都是函数对象的属性
    eat.apply(修改的this对象,[eat的参数1,参数2...]);
    eat.call(修改的this对象,eat的参数1,参数2...);
apply,call,bind的异同?
    1.它们都是用来改变函数对象的this指向
    2.bind通常针对于匿名函数,apply和call针对有名函数
    3.apply,call第二个参数不同,apply为数组,call单独写出
    4.bind方法调用时,并不是直接调用原函数,等价创造了一个新的函数对象,还需要重新调用