导航

js call & apply

Posted on 2012-09-19 16:11  surealland  阅读(134)  评论(0编辑  收藏  举报

//基本用法

function A(){
    this.name='A';
    this.func=function(x,y){
        console.log(this.name,x+y);
    }
}

function B(){
    this.name='B';
}

var a=new A();
var b=new B();

//b调用a的func.
a.func.call(b,5,6);//B 11
a.func.apply(b,[5,6]);//B 11

//升级用法  B“继承”A

function A(name){
        this.a='a';
        this.name=name;
        this.showName=function(a,b){
            console.log(a+b);
        }
    }
    function B(name){
        A.call(this,name);
    }
    B.prototype=new A();
    B.prototype.bfunc=function(){
        console.log('bfunc');
    }
    var bb=new B('bbbbb');
    
    console.log(bb instanceof A);//true
    console.log(bb instanceof B);//true
    console.dir(bb);