zoukankan      html  css  js  c++  java
  • js中bind(),call()使用详解

    1.bind()

    函数.bind(this指向,函数参数...)

    1 函数调用bind会返回一个新的函数
    2 新函数中的this指向bind的第一个参数

    例:
    function show() {
          console.log('show');
          console.log(this);
        }
    show();// this指向window
    var obj = {
          name: 'zs'
        };
    
    var fn = show.bind(obj); // 由于返回的是新函数,也可以写成
    fn();// this指向obj
    // 由于返回的是新函数,也可以写成↓
    // var fn = show.bind(obj)();
    this指向:

    2. bind()行内事件this指向

    <div onclick="fn(this)"> 只愿君心似我心,定不负相思意</div>
      <!-- 行内绑定改变this的指向 -->
      <div onclick="fn1.bind(this)()"> 你猜猜</div>
      <script>
        function fn(that) {
          console.log(that); // 只愿君心
    
          // console.log(this);
    
        }
    
        function fn1() {
          console.log(this); // 你猜猜
        }
      </script>
     
  • 相关阅读:
    Game Engine Architecture 3
    Game Engine Architecture 2
    补码
    工厂模式
    Game Engine Architecture 1
    YDWE Keynote
    3D Math Keynote 4
    3D Math Keynote 3
    3D Math Keynote 2
    OGRE中Any 类型的实现
  • 原文地址:https://www.cnblogs.com/MoonASixpence/p/14757292.html
Copyright © 2011-2022 走看看