JS里的函数的call()与back()方法


function cat(){}
cat.prototype={  food:"fish", say: function(){ alert("I love "+this.food)}
var blackCat = new cat;
blackCat.say()

  

 

现在有WhiteCat={food:'rice'},就有了我们不想对它重新定义say方法,那么我们可以通过call或apply用blackCat的say方法:blackCat.say.call(whiteDog);

call 和 apply 都是为了改变某个函数运行时的 context 即上下文而存在的,换句话说,就是为了改变函数体内部 this 的指向。

因为 JavaScript 的函数存在「定义时上下文」和「运行时上下文」以及「上下文是可以改变的」这样的概念

我们知道,Array.prototype.slice.call(arguments)能将具有length属性的对象转成数组,除了IE下的节点集合

(因为ie下的dom对象是以com对象的形式实现的,js对象与com对象不能进行转换)

var a={length:2,0:'first',1:'second'};
Array.prototype.slice.call(a);//  ["first", "second"]
 
var a={length:2};
Array.prototype.slice.call(a);//  [undefined, undefined]

 

posted @ 2018-04-25 15:46  Jack-liu  阅读(260)  评论(0编辑  收藏  举报