首页 > 移动平台 > 详细

JS中的Call()和Apply()

时间:2015-08-18 13:38:02      阅读:270      评论:0      收藏:0      [点我收藏+]

1.常用实例

function add (a,b){

  alert(a+b);

}

function sub(a,b){

  alert(a-b);

}

add.call(sub,4,3);相当于add(4,2);

2.改变作用哉

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有同名showName方法也不会执行。

animal.showName.call(cat,",")==animal.showName.apply(cat,[]);  输出结果为Cat

3.实现继承

 function Animal(name){

  this.name=name;

  this.showName= function(){

    alert(this.name);

  }

}

function Cat(name){

//Animal.call(this) 的意思就是使用 Animal对象代替this对象,那么 Cat中不就有Animal的所有属性和方法了吗,Cat对象就能够直接调用Animal的方法以及属性了.

  Animal.call(this, name);

}

var cat = new Cat("Black Cat");

cat.showName();

4.多重继承

function Class10(){

  this.showSub= function(a,b){

    alert(a-b);

  }

}

function Class11(){

  this.showAdd = function(a,b){

    alert(a-b);

  }

}

function Class2(){

  Class10.call(this);

  Class11.call(this);

}

JS中的Call()和Apply()

原文:http://www.cnblogs.com/liangxuru/p/4738924.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!