宿主对象,在javascript中有三类对象,本地对象,内置对象和宿主对象。其他两类暂且不提,宿主对象是指什么呢(DOM BOM),控制台对象是文档对象模型的扩展,也被认为是宿主对象。那么,它们有什么缺陷呢?在IE9之前,宿主对象不是继承自Object,它们的方法也不继承自Function,IE9之后就大有改进了。

看下IE8与IE9的document.getElementById

ie8:

ie9:

我们可以看到,ie9的document.getElementById是有Function.prototype上的方法的,所以说,IE9+的宿主对象它们继承了Object,方法继承了Function。

IE8不支持call,所以问题就来了,我们经常会有这样的需求,比如,重新控制台。

很多人想到了console.log.call,但是它不完美,现在你们知道了~~

好,想想解决办法吧:

1、使用Function.prototype.bind,但是...你得为不支持bind的浏览器做兼容

Function.prototype.bind.call(console.log,console).apply(console,arguments)
//摘自MDN
if (!Function.prototype.bind) {
Function.prototype.bind = function (oThis) {
if (typeof this !== "function") {
// closest thing possible to the ECMAScript 5 internal IsCallable function
throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
} var aArgs = Array.prototype.slice.call(arguments, 1),
fToBind = this,
fNOP = function () {},
fBound = function () {
return fToBind.apply(this instanceof fNOP && oThis
? this
: oThis || window,
aArgs.concat(Array.prototype.slice.call(arguments)));
}; fNOP.prototype = this.prototype;
fBound.prototype = new fNOP(); return fBound;
};
}

2、new Function+replace (new Function不是说尽量不要用么,还是算了吧!!)

function log(){

    var fn = 'console.log(args)',

    args=[].slice.call(arguments);

    fn = new Function('args',fn.replace(/args/,args.join(',')));

    fn(arguments);

};

3、终极方法

Function.prototype.apply.call(console.log,console,arguments);

这么一对比,第三种方案妥妥的胜出啊,不用考虑兼容,代码简短,虽然不是很好理解~~

说了这么多废话,Function.prototype.apply.call什么时候用,就是在这种应用场景。

如果还有其他的话,那就是那些奇葩面试题,比如:

var f1=function(){console.log(1)};
var f2=function(){console.log(2)};
Function.prototype.call.call(Function.prototype.call,f2)//
Function.prototype.call.call(f1,f2);//

最新文章

  1. 7.Struts2复杂类型数据的接受
  2. play 源码分析
  3. android studio 使用 jni 编译 opencv 完整实例 之 图像边缘检测!
  4. 分布式中使用Redis实现Session共享(一)
  5. An error in projects
  6. windbg学习!vad
  7. hdu 4393 优先队列
  8. poj 2631 Roads in the North
  9. UVA 11754 Code Feat 中国剩余定理+暴力
  10. 记录一次mount问题
  11. 3.java.lang.ClassNotFoundException
  12. [每日一题] OCP1z0-047 :2013-07-15 drop column
  13. HUST 1372 marshmallow
  14. Spring还使用基于 JSR-250 注释,它包括 @PostConstruct, @PreDestroy 和 @Resource 注释
  15. [刷题]算法竞赛入门经典(第2版) 5-16/UVa212 - Use of Hospital Facilities
  16. linux中普通的文件查看操作(cat、more、less、head、tail)
  17. java中引用的概念
  18. 析构函数 声明为protected
  19. WIN10 + VS 2013 配置Opencv2.4.1.3 32位
  20. 洛谷 P4148 简单题 解题报告

热门文章

  1. 洛谷【P3612】[USACO17JAN]Secret Cow Code秘密奶牛码
  2. Canal入门
  3. 【转】js中select的基本操作
  4. 插曲一--记《数据结构与问题求解(Java语言版)(第4版)》翻译问题
  5. LAMP 1.4 PHP编译安装问题解决
  6. Spring示例工程
  7. NIO和Reactor
  8. Codeforces Round #279 (Div. 2) C. Hacking Cypher (大数取余)
  9. .net core 中的配置文件
  10. [CentOS7] parted用于磁盘分区(同时支持GPT和MBR分区表)