当前位置

网站首页> 程序设计 > 开源项目 > 程序开发 > 浏览文章

call/apply的理解与实例分享

作者:小梦 来源: 网络 时间: 2024-04-01 阅读:

call/apply 都是为了改变某个函数的执行上下文而存在的,换句话说就是为了改变函数的this指向。 除了传递参数时有所差别,call和apply作用完全一样.

其中apply传递的参数为数组形式, call传递的参数为按顺序依次排列

// 当参数个数不确定或者你觉得用apply比较爽时, 就直接使用apply// 字面解释就是obj夺舍fn,obj拥有了执行fn函数的能力,并且this指向obj.var arguments = { 0:'name', 1:'age', 2:'gender' };fn.apply(obj, arguments);fn.call(obj, name, age, gender);

下面我收集了几个我遇到过的实际例子

  • 将类数组形式转换为数组 example

// arguments// 返回值为数组,arguments保持不变var arg = [].slice.call(arguments);// nodeListvar nList = [].slice.call(document.getElementsByTagName('li'));
  • 方法借用 example

var foo = {    name: 'joker',    showName: function() {        console.log(this.name);    }};var bar = {    name: 'rose'};foo.showName.call(bar); // rose
  • 在继承中的应用 example

// parentvar Person = function(name) {    this.name = name;    this.gender = ['man', 'woman'];}// childvar Student = function(name, age) {    // inherit    Person.call(this);}Student.prototype.message = function() {    console.log('name:'+this.name+', age:'+this.age+', gender:.'+this.gender[0]);}var xm = new Student('xiaom', 12);xm.message(); //name:undefined, age:undefined, gender:.man
  • 封装对象时保证this指向 example

var Nicco = function(name) {    this.name = name;}Nicco.prototype = function() {    constructor: Nicco,    message: function() {        var _this = this;        addEventListener('mousedown',function() {    // stay this    return _this.fndown.call(_this);},false        );    },    fndown: function() {        var_this = this,str = this.name + ', i miss you.';        addEventListener('mouseup',function() {    return _this.fnup.call(_this, str);},false        );    },    fnup: function(str) {        console.log(str);    }}

热点阅读

网友最爱