代码改变世界

函数对象

2015-10-09 23:25  little白  阅读(198)  评论(0编辑  收藏  举报

1函数即对象

 function add1(a,b){
        return a+b;
    }

 var add2 = new Function("a","b","return a+b");

    alert(add1(1,2))//3
    alert(add2(1,2))//3

2 arguments类数组对象

arguments只有在代码运行的时候才起作用,保存函数的实参,类数组是说它不能使用数组的方法
 function add(a,b,c,d){
        alert(arguments.length);
        alert(arguments[0]);
    }
    add();//0
    add(1);//1
    add("aa",1,88)//3

3 函数对象的length属性可以获取到函数的形参

function checkVarCount(a, b){
        if (checkVarCount.length == arguments.length) {
            alert("形参和实参个数一样");
        }else{
            alert("形参和实参的个数不一样");
        }
    }
    checkVarCount(1, 2);//形参和实参个数一样
    checkVarCount(1);   //形参和实参的个数不一样

4 call方法借用(注意书写的顺序,借用谁的方法将谁写前边)

var myclass={getAllStudentsNumbers:function(){alert("success")}};
var student={getDetail:function(){return {name:'pxx',aihao:'唱歌跳舞'}}};
myclass.getAllStudentsNumbers.call(student)

//call传参
//函数其实也是对象
function add(a, b)
{
alert(a + b);
}
function sub(a, b)
{
alert(a - b);
}
add.call(sub, 3, 1);
 

4.1 call this(可以改变上下文)

    function Animal(){
        this.name = "Animal";
        this.showName = function(){
            alert(this.name);
        }
    }
   
    function Cat(){
        this.name = "Cat";
    }

    var animal = new Animal();
    var cat = new Cat();

    //通过call或apply方法,将原本属于Animal对象的showName()方法交给当前对象cat来使用了。
    //结果为"Cat"
    animal.showName.call(cat);
   

 

5 apply 和call的区别

apply: Function.prototype.apply
call:Function.prototype.call

NOTE: While the syntax of this function is almost identical to that of call(), the fundamental difference is that call() accepts an argument list, while apply() accepts a single array of arguments. 
call 和 apply 的区别只在于这两个函数接受的参数形式不同。

Example: 
判断一个变量是不是Array

  1. var a = {};
  2. var b = []
  3. Object.prototype.toString.call(a); // 输出为: "[object Object]" 
  4. Object.prototype.toString.call(a); // 输出为: "[object Array]"

使用call和apply方法,可以改变对象方法的运行环境,例如,有一个类Man

function Man() {}
Man.prototype = {
    valet: false,
    wakeUp: function(event) {
        console.log(this.valet + "? Some breakfase, please.");
    }
};

//get "undefined? Some breakfast, please
var button = document.getElementById('morning');
button.addEventListener(
    "click",
    wooster.wakeUp,
    false
);

//使用apply来改变 wakeUp 的上下文环境,即 wakeUp 中的this
var button = document.getElementById('morning2');
button.addEventListener(
    "click",
    function() {
        Man.prototype.wakeUp.apply(wooster, arguments);
    },
    false
);

ps:以上代码例子来自与《深入Ajax架构与最佳实践》3.1 对象与事件触发

太晚了,对这两个方法我的理解还是很欠缺,后面有时间继续补充=。=