请选择 进入手机版 | 继续访问电脑版
开启辅助访问
帐号登录 |立即注册

js中 call() 和 apply() 方法的区别和用法详解

 
每个函数都包含两个非继承而来的方法:call()和apply();在JavaScript中,call和apply作用是一样的,都是为了改变某个函数运行时的上下文(context)而存在的,换句话说,就是为了改变函数体内部this的指向。
[JavaScript] 纯文本查看 复制代码
function fruits(){}[/backcolor][backcolor=yellow]        
fruits.prototype = {
    color: "red",
    say: function(){
        console.log("My color is " + this.color);
    }
};

var apple = new fruits;
apple.say();   


当想另外一个对象想使用fruits中的say方法时不用重新写,使用call和apply可以实现“劫持”别人的方法。
[JavaScript] 纯文本查看 复制代码
function fruits(){}
            
fruits.prototype = {
    color: "red",
    say: function(){
        console.log("My color is " + this.color);
    }
};

var another = {
    color: "yellow"
};

var apple = new fruits;
apple.say();                //My color is red
apple.say.call(another);    //My color is yellow
apple.say.apply(another);   //My color is yellow

区别:参数书写方式不同call(thisObj, arg1, arg2, arg3, arg4);
apply(thisObj, [args]);
thisObj:call和apply第一个参数是一样的,该参数将替代Function类里面的this对象。
arg1,arg2....:是一个个的参数,
args:一个数组或类数组,是一个参数列表。


用法改变函数作用域
[JavaScript] 纯文本查看 复制代码
var name = "小白";
var obj = {
    name: "小红"
};

function sayName() {
    return this.name;
}
console.log(sayName.call(this));   //小白
console.log(sayName.call(obj));    //小红

实现继承
[JavaScript] 纯文本查看 复制代码
//实现js继承
//父类
function Person(name, height) {
    this.sayInfo = function() {
        return "姓名:" + name + ", 身高:" + height + ", 体重:" + this.weight;
    }
}
//子类
function Chinese(name, height, weight) {
    Person.call(this, name, height);
    this.weight = weight;
    
    this.nation = function() {
        console.log("我是中国人");
    }
}
//子类
function America(name, height, weight) {
    Person.apply(this, [name, height]);
    this.weight = weight;
}

let chiness = new Chinese("成龙", "178cm", "60kg");
console.log(chiness.sayInfo());    //姓名:成龙, 身高:178cm, 体重:60kg
let america = new America("jack", "180cm", "55kg");
console.log(america.sayInfo());    //姓名:jack, 身高:180cm, 体重:55kg





回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

友情链接
  • 艾Q网

    提供设计文章,教程和分享聚合信息与导航工具,最新音乐,动漫,游戏资讯的网站。