您的位置:首页 > 移动开发

1.JS设计模式-this,call&apply

2015-10-10 18:49 295 查看

1. this,call&apply

1.1 this

this是Javascript语言的一个关键字。

它代表函数运行时,自动生成的一个内部对象,只能在函数内部使用。

1.1.1 普通函数调用

这是函数的最通常用法,属于全局性调用,因此this就代表全局对象Global。

请看下面这段代码,它的运行结果是1。

  function test(){

    this.x = 1;

    alert(this.x);

  }

  test(); // 1

为了证明this就是全局对象

1.1.2 对象方法的调用

函数还可以作为某个对象的方法调用,这时this就指这个上级对象。

  function test(){

    alert(this.x);

  }

  var o = {};

  o.x = 1;

  o.m = test;

  o.m(); // 1

1.1.3 构造函数调用

所谓构造函数,就是通过这个函数生成一个新对象(object)。这时,this就指这个新对象。

  function test(){

    this.x = 1;

  }

  var o = new test();

  alert(o.x); // 1

运行结果为1。

1.1.4 apply调用

apply()是函数对象的一个方法,它的作用是改变函数的调用对象,它的第一个参数就表示改变后的调用这个函数的对象。因此,this指的就是这第一个参数。

  var x = 0;

  function test(){

    alert(this.x);

  }

  var o={};

  o.x = 1;

  o.m = test;

  o.m.apply(); //0

apply()的参数为空时,默认调用全局对象。因此,这时的运行结果为0,证明this指的是全局对象。

如果把最后一行代码修改为

  o.m.apply(o); //1

运行结果就变成了1,证明了这时this代表的是对象o。

 

1.2 call &apply

apply() 方法在指定 this 值和参数(参数以数组或类数组对象的形式存在)的情况下调用某个函数。

fun.apply(thisArg[, argsArray])

 

call() 方法在使用一个指定的this值和若干个指定的参数值的前提下调用某个函数或方法.

fun.call(thisArg[, arg1[, arg2[, ...]]])

 

1.2.1 改变对象的this指向

    function Obj(){this.value="对象!";}

    var value="global 变量";

    function Fun1(){alert(this.value);}

    window.Fun1();   //global 变量

    Fun1.call(window);  //global 变量

    Fun1.call(document.getElementById('myText'));  //input text

    Fun1.call(new Obj());   //对象!

call函数和apply方法的第一个参数都是要传入给当前对象的对象,及函数内部的this。

1.2.2 借用方法

var numbers = [5, 458 , 120 , -215 ];

var maxInNumbers = Math.max.apply(Math, numbers),   //458

   maxInNumbers = Math.max.call(Math,5, 458 , 120 , -215); //458

number 本身没有 max 方法,但是 Math 有,我们就可以借助 call 或者 apply 使用其方法

1.2.3 bind

bind()方法会创建一个新函数,称为绑定函数,当调用这个绑定函数时,绑定函数会以创建它时传入 bind()方法的第一个参数作为 this,传入 bind() 方法的第二个以及以后的参数加上绑定函数运行时本身的参数按照顺序作为原函数的参数来调用原函数。

fun.bind(thisArg[, arg1[, arg2[, ...]]])

 

调用,希望方法中的 this 是原来的对象。(比如在回调中传入这个方法。)如果不做特殊处理的话,一般会丢失原来的对象。从原来的函数和原来的对象创建一个绑定函数,则能很漂亮地解决这个问题:

 

this.x = 9;

var module = {

  x: 81,

  getX: function() { return this.x; }

};

 

module.getX(); // 81

 

var getX = module.getX;

getX(); // 9, 因为在这个例子中,"this"指向全局对象

 

// 创建一个'this'绑定到module的函数

var boundGetX = getX.bind(module);

boundGetX(); // 81

 

自己实现bind函数:

Function.prototype.bind = function(context){ 

  var args = Array.prototype.slice(arguments, 1),

  F = function(){},

  self = this,

  bound = function(){

      var innerArgs = Array.prototype.slice.call(arguments);

      var finalArgs = args.concat(innerArgs);

      return self.apply((this instanceof F ? this : context), finalArgs);

  };

 

  F.prototype = self.prototype;

  bound.prototype = new F();

  return bound;

};

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: