JavaScript之call实例详解

来源:互联网 发布:淘宝好看的女装店 编辑:程序博客网 时间:2024/06/01 10:43

call()方法是做什么用的呢?与其看枯燥的文字解释,还不如看看他都可以用来做些什么来的实惠!
但是还要大概知道一下比较好
function.call(thisobj,args…)
call将指定函数function作为thisobj对象的方法来调用,将参数args传递给function,返回值为function的返回值。
thisobj是调用function的对象,在函数主体内thisobj是this的值,若thisobj为null,就使用全局对象

1、

?

function add(a,b){

    alert(a+b);

}

function sub(a,b){

    alert(a-b);

}

add.call(sub,3,1);

解释:add方法作为sub对象(javascript中函数即为对象)的方法调用,结果为4

2、

?

function Class1(){

    this.name = "class1";

    this.showName = function(){

        alert(this.name);

    }

}

function Class2(){

    this.name = "class2";

}

var c1 = new Class1();

var c2 = new Class2();

 

c1.showName.call(c2);

解释:c1.showName方法作为c2对象的方法调用
Class2中并没有showName方法,使用call后,可以调用到c1中的showNam方法

3、

?

function Product(name, price) {

  this.name = name;

  this.price = price;

 

  if (price < 0)

    throw RangeError('Cannot create product "' + name + '" with a negative price');

  return this;

}

 

function Food(name, price) {

  Product.call(this, name, price);

  this.category = 'food';

}

Food.prototype = new Product();

 

function Toy(name, price) {

  Product.call(this, name, price);

  this.category = 'toy';

}

Toy.prototype = new Product();

 

var cheese = new Food('feta', 5);

var fun = new Toy('robot', 40);

解释:这里的call用于连接另一个对象的constructor,有点像java中的super()。Food中的this指向Food的作用域,就相当于在Food作用域下调用Product函数.

4、

?

var animals = [

  {species: 'Lion', name: 'King'},

  {species: 'Whale', name: 'Fail'}

];

 

for (var i = 0; i < animals.length; i++) {

  (function (i) {

    this.print = function () {

      console.log('#' + i  + ' ' + this.species + ': ' + this.name);

    }

  }).call(animals[i], i);

}

解释:这里的call用于调用匿名函数,匿名函数作为数组中的对象的方法进行调用

5、

?

function Class1(){

    this.showTxt = function(txt){

        alert(txt);

    }

}

 

function Class2(){

    Class1.call(this);

}

 

var c2 = new Class2();

 

c2.showTxt("cc");

解释:这里利用call实现了继承

6、

?

function ClassA(){

    this.showSub = function(a,b){

        alert(a-b);

    }

}

function ClassB(){

    this.showAdd = function(a,b){

        alert(a+b);

    }

}

 

function ClassC(){

    ClassA.call(this);

    ClassB.call(this);

}

解释:这里使用call实现了多继承

转自:http://www.veryued.org/2011/09/javascript-call/

原创粉丝点击