zoukankan      html  css  js  c++  java
  • call和apply方法的理解

    第一种:直接先来个粟子吧、、、
    function cat(){
    }
    cat.prototype={
    food:"fish",
    say: function(){
    alert("I love "+this.food);
    }
    }
     
     
    var blackCat = new cat;
    whiteDog = {food:"bone"};
    blackCat.say.call(whiteDog); //I love bone
    whiteDog对象并没有say方法,当我们不能重新定义的时候,我们可以通过call或者apply使用其它对象(p这里是blockCat)的方法去操作(实现say方法);
    由此可以看出call和apply是为了动态的改变this而出现的,当一个object没有某个方法,但是其它的对象有,我们就可以借助call或者apply用其它对象的方法来操作。

    其中、用的比较多的就是通过 document.getElementsByTagName选择的dom节点是一种类似array的array,但它不能应用Array下的push.pop等方法,我们可以通过
    var domNodes = Array.prototype.slice.call(document.getElementsByTagName("*"));这样domNodes对象就可以使用Array的所有方法了。

    第二种:
    obj.call(thisObj,arg1,arg2,....);
    obj.apply(thisObj,[arg1,arg2,....]);
    这两种方法都一样,都是把obj(即this)绑定到thisObj,这时候thisObj就具有了obj的属性和方法或者说thisObj继承了obj的属性和方法,绑定后会立即执行函数 ,它们在这方面的唯一区别就是apply接受的是数组,call接受的连续的参数 
    add(5,3); //8
    add.call(sub, 5, 3); //8
    add.apply(sub, [5, 3]); //8
     
    sub(5, 3); //2
    sub.call(add, 5, 3); //2
    sub.apply(add, [5, 3]); //2
    第三种:实现继承
    var Perent = function(){
    this.name = "test";
    this.age = 23;
    }
     
    var child = {};
    console.log(child); //Object() 对象
    Parent.call(child);
    console.log(child); //Object{name:'test',age:23}
  • 相关阅读:
    hdu5754_找规律+威佐夫博弈
    codeforce645C_尺取法
    hdu4336_容斥dp
    poj3071_概率dp
    codeforces148D_推论题
    poj2151_概率dp
    hdu3853_概率dp
    POJ 1410 判断线段与矩形交点或在矩形内
    POJ 1066 Treasure Hunt 线段相交判断
    POJ 2653 Pick-up sticks 判断线段相交
  • 原文地址:https://www.cnblogs.com/EvileOn/p/6064733.html
Copyright © 2011-2022 走看看