zoukankan      html  css  js  c++  java
  • 函数的属性和方法(apply()、call())

    //length属性:表示函数希望接收的命名参数的个数
    //prototype属性:保存所有实例方法的地方,如toString()和valueOf()都保存在prototype下
    console.log("函数的属性length,prototype");
    function sayName(name) {
        alert(name);
    }
    
    function sum(num1, num2) {
        return num1 + num2;
    }
    
    function sayHi() {
        alert('hi');
    }
    
    console.log(sayName.length);//1
    console.log(sum.length);//2
    console.log(sayHi.length);//0
    
    /*
    *apply()和call()方法:改变函数体内this对象的值(可以理解为作用域),真正的作用是可以扩充函数赖以运行的作用域
    *apply()接收两个参数,第一个为作用域(也就是要改变this所指向的值),第二个参数为参数数组,可以是Array的实例,也可以是arguments对象
    *call()方法与apply()方法作用相同,区别在于接收参数的方式不同,第一个为作用域,其他的为要传入的参数,以枚举的方式传入
    */
    console.log("apply()方法和call()方法");
    function sum2(num1, num2) {
        return num1 + num2;
    }
    
    function callSum1(num1, num2) {
        return sum2.call(this, num1, num2);//sum2的作用域设置成callSum1,传入callSum1的参数num1, num2
    }
    
    function callSum2(num1, num2) {
        return sum2.apply(this, arguments);//sum2的作用域设置成callSum1,传入callSum2的参数arguments
    }
    
    console.log(callSum1(1, 2));//3
    console.log(callSum2(3, 2));//5
    
    //扩充函数运行的作用域
    console.log("扩充函数运行的作用域");
    
    window.color = "red";
    var o = {color: "blue"};
    
    function sayColor() {
        console.log(this.color);
    }
    
    sayColor(this);//red
    sayColor(window);//red
    sayColor(o);//blue
  • 相关阅读:
    linux 进程间通信之pipe
    makefile详解
    makefile基础
    std::list 源代码解析
    各类编译器 allocator 底层
    oop &&GP 模板 ---> 特化和偏特化
    STL Allocator
    关联式容器
    vector::erase
    maven
  • 原文地址:https://www.cnblogs.com/qiangspecial/p/3129865.html
Copyright © 2011-2022 走看看