zoukankan      html  css  js  c++  java
  • bind()

    首先是改变this指向问题

     1 var altwrite = document.write;

    2 altwrite("hello"); 

    上面的程序运行,会报错:Uncaught TypeError: Illegal invocation  非法调用

    报错的原因就是this指向问题,因为altwrite指向的是windowd对象,而write指向的是document对象

    我们可以通过bind()修改altwrite的上下文,把它指向document,就可以了,修改如下:

     1 var altwrite = document.write;

    2 altwrite.bind(document)("hello"); 

    当然也可以使用call()方法:

     1 altwrite.call(document, "hello") 

    绑定函数

    bind()最简单的用法是创建一个函数,使这个函数不论怎么调用都有同样的this值。

    将方法从对象中拿出来,然后调用,并且希望this指向原来的对象。如果不做特殊处理,一般会丢失原来的对象。使用bind()方法能够很漂亮的解决这个问题:

     1   this.num = 9;
     2     var mymodule = {
     3         num: 81,
     4         getNum: function() {
     5             return alert(this.num);
     6         }
     7     };
     8 
     9     mymodule.getNum();//81
    10 
    11     var getNumb = mymodule.getNum;
    12     getNumb();// 9  这个函数里面的this指向的是全局对象
    13 
    14     //创建一个this绑定到mydule的函数
    15     var boundGetNum = getNumb.bind(mymodule);
    16     boundGetNum(); // 81
  • 相关阅读:
    实现Callable接口实现多线程
    匿名内部类方式实现
    实现Runnable接口方式
    后台线程
    继承Thread类
    线程中断详解
    第六章、Linux 的档案权限不目彔配置
    安装virtual box
    CISCO实验记录六:EIGRP路由协议
    zabbix监控项整理Items-key
  • 原文地址:https://www.cnblogs.com/colaman/p/6266529.html
Copyright © 2011-2022 走看看