call()与构造函数的运用

一、简介

call()和apply()方法是所有函数体的固有属性,可以在指定作用域下调用函数。这里面有两层意思:1.可以在另外的作用域下调用函数;2.当函数体是是构造函数时,call()方法能达到类之间继承的效果。

二、call()

1.调用函数

下面举例说明:

var a = function (){
    console.log('aaa')
}

var b = function (){
    a.call(this);
}
b();  //输出 aaa

a.call(this)等效于a(),即是在b函数的作用域下调用了a();这种用法意义不大,理解就行。 

2.构造函数继承

call()方法主要在面向对象编程中使用,可在不同类(构造函数)中继承。

var A = function(){
    this.a = function(){
        console.log('aaa')
    };
    this.name = 'a';
    console.log('this is a');
}

var B = function (){    
    A.call(this); 
    this.num = '2';
}

var boo = new B();    //this is a
boo.a();    //aaa
console.log(boo.name);    //a
console.log(boo.num);    //2

A、B都是构造函数,A.call(this)即是在B作用域下调用A构造函数。因此,B继承了A的属性、方法,同时调用了A构造函数。B的实例将拥有A的所有特性。

下面我们再来看个例子:

var A = function(){
    this.a = function(){
        console.log('aaa')
    };
    this.name = 'a';
    console.log('this is a');
}

var B = function (){    
    A.call(this);  
    this.num = '2';
}

var c = {}  
B.call(c);    //this is a
c.a();    //aaa
console.log(c.name);    //a
console.log(c.num);    //2

定义对象c(非构造函数),再c的作用域下调用B构造函数,c对象也会继承B的所有属性、方法。这是一个对象实例和构造函数的区别。

原文地址:https://www.cnblogs.com/lodadssd/p/7475274.html