javascript 【对象冒充】 apply 用法(后期补充call)

1、定义:apply在指定对象(this)和参数(参数以数组或类数组对象的形式存在)下调用某个函数,用法F1.apply(F2,[arr1,arr2]);如没有参数下参数可以用null替代;

2、应用:

  (1)构造函数实现继承

function F1(name,age){
        this.name=name;
        this.age=age;
        this.sayName=function(){
            console.log(this.name+"~"+this.age);
        }
    }
    
    function F2(name,age){
        this.name=name;
        this.age=age;
        F1.apply(this,arguments);
    }

    var f1=new F1("zhang",28);
    var f2=new F2("wang",22);
    f1.sayName();
    f2.sayName();

上述例子可以看出F2中并没有sayName方法,通过apply实现了 F1的继承;

(2)非构造函数的用法:

  例子1

apply继承方法(非构造函数)
    function F2(){
        this.name="fff222";
        this.sayName=function(){
            console.log(this.name);
        }
    }
    function F1(){
        this.name="fff111";
    }
    var f1=new F1();
    var f2=new F2();
    f2.sayName.apply(f1,null);
    f2.sayName();

例子1通过函数外apply应用实现的sayName冒充

  例子2

function F2(){
        this.name="fff222";
        this.sayName=function(){
            console.log(this.name);
        }
    }
    function F1(){
        //this.name="fff111";    //影响继承后的属性
        F2.apply(this,null);
        this.name="fff111";
    }
    var f1=new F1();
    var f2=new F2();
    f1.sayName();
    f2.sayName();

例子2是函数内实现方法继承,但要注意函数内属性的声明定义和apply使用的顺序!~

 

 

 

javascript中Call方法的使用:

function Person(name){
    this.name = name;
    this.sayName = function(){
        console.log(this.name);
    };
}

var person = new Person("yuanr");
person.sayName();
var obj = {"name":"yuanr6039"};
person.sayName.call(obj);

 

description: call() 接收俩个参数,1、方法中使用调用对象this值,2、方法所需的参数数组[];

上面例子中,obj通过call方法使用了 person的方法sayName(); 实现了 obj中name值的输出!

 

新手菜鸟纯个人学习笔记 望大神批评指正!

posted on 2016-01-12 11:53  源人  阅读(183)  评论(0)    收藏  举报

导航