[JS] Topic - hijack this by "apply" and "call"

Ref: 详解js中的apply与call的用法

 

call 和 apply二者的作用完全一样,只是接受参数的方式不太一样。

 

参数形式:

Function.apply(obj,args)

call方法apply方法的第一个参数是一样的,只不过第二个参数是一个参数列表

 

非严格模式下的第一个参数:

var test = function(){
  console.log(this===window);
}

// this会指向默认的宿主对象,在浏览器中则是window
test.apply(
null);//true test.call(undefined);//true

 

一般的用法:

"劫持"别人的方法 

var foo = {
  name:"mingming",
  logName:function(){
    console.log(this.name);
  }
}
var bar={ name:"xiaowang" };

/**
* bar挟持foo的方法logName
*/ foo.logName.call(bar);
//xiaowang

 

实现继承

function Animal(name){   
  this.name = name;   
  this.showName = function(){   
    console.log(this.name);   
  }   
}   
 
function Cat(name){  
/**
* this(Cat)挟持Animal的属性name
*/ Animal.call(
this, name); } var cat = new Cat("Black Cat"); cat.showName(); //Black Cat

 

在实际开发中,经常会遇到this指向被不经意改变的场景。

(1) 有一个局部的fun方法,fun被作为普通函数调用时,fun内部的this指向了window,但我们往往是想让它指向#test节点,见如下代码:

window.id="window";
document.querySelector('#test').onclick = function(){
console.log(
this.id);//test var fun = function() { console.log(this.id); }
fun();
//window }

 

(2) 使用call,apply我们就可以轻松的解决这种问题了

window.id="window";
document.querySelector('#test').onclick = function(){
  console.log(this.id);//test
  var fun = function(){
    console.log(this.id);
  }
fun.call(
this);//test }

 

(3) 通过中间变量的技巧:

window.id="window";
document.querySelector('#test').onclick = function(){
  var that = this;
  console.log(this.id);//test
  var fun = function(){
    console.log(that.id);
  }
  fun();//test
}

 

类数组:

例如: arguments, NodeList

1.具有length属性

2.按索引方式存储数据

3.不具有数组的push, pop等方法

 

  • Array.prototype.push 页可以实现两个数组合并
(function() {
  Array.prototype.push.call(arguments, 4);  // 往arguments中push一个4进去了
  console.log(arguments);//[1, 2, 3, 4]
})(1,2,3)

 

  • 使用apply,支持数组:
var arr1=new Array("1","2","3"); 
var arr2=new Array("4","5","6"); 

// arr1调用了push方法,参数是通过apply将数组装换为参数列表的集合. Array.prototype.push.apply(arr1, arr2); console.log(arr1);
//["1", "2", "3", "4", "5", "6"]

  

求类数组中的最大值:

(function(){
  var maxNum = Math.max.apply(null, arguments);
  console.log(maxNum);//56
})(34,2,56);

 

判断类型:

console.log(Object.prototype.toString.call(123)) //[object Number]
console.log(Object.prototype.toString.call('123')) //[object String]
console.log(Object.prototype.toString.call(undefined)) //[object Undefined]
console.log(Object.prototype.toString.call(true)) //[object Boolean]
console.log(Object.prototype.toString.call({})) //[object Object]
console.log(Object.prototype.toString.call([])) //[object Array]
console.log(Object.prototype.toString.call(function(){})) //[object Function]

 

posted @ 2018-04-17 07:30  郝壹贰叁  阅读(242)  评论(0编辑  收藏  举报