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
  • 相关阅读:
    Java类与对象
    读《大道至简——团队缺乏的不只是管理》有感
    java课后作业
    c++ 创建单项链表
    c++ 结构指针和双向链表
    c++ 自定义数据结构运用
    c++ 时间函数和结构化数据
    c++ 结束程序的几种方式
    c++ main函数的参数
    c++ 参数个数可变的函数
  • 原文地址:https://www.cnblogs.com/colaman/p/6266529.html
Copyright © 2011-2022 走看看