zoukankan      html  css  js  c++  java
  • Javascript百学不厌

    最近看了一本书,让自己的野路子走走正规路线

    方法调用模式:

      方法:当一个函数被保存为对象的一个属性时,我们称它为一个方法。

    var obj = {
          fun1: function() {this} // 这时的 this 指向 obj
        }
        obj.fun1()

    函数调用模式:

      

    var obj = {
          fun1: function() {this},
          fun2: function() {
            var fun3 = function(){
              this...  // 这时的 this 指向 window
            }
            fun3();
          }
        }
        obj.fun2()

    这个时候认为的习惯是指向 obj 。 为了解决这个问题  var _this = this 将obj 的this保存起来就可以了。

    var obj = {
          fun1: function() {this},
          fun2: function() {
            var _this = this;  // 这里是方法调用模式 this 指向obj
            var fun3 = function(){
              _this  // 不解释了
            }
            fun3();
          }
        }
        obj.fun2()

    ES6 箭头函数中的this

    function taskA() {
      this.name = 'hello'
    
      var fn = function() {
        console.log(this) // 输出 window 因为是 函数调用模式,所以指向window
        console.log(this.name)
      }
    
      var arrow_fn = () => {
        console.log(this) // 输出 window 因为箭头函数自己没有this,于是向上找到taskA()中的this,而taskA()是函数调用模式,所以它的this 指向window
        console.log(this.name)
      }
      fn()
      arrow_fn()
    }
    taskA()

    我们也可以通过 bind  call  apply 三个函数来强行指定this, 至于这三种方法就不赘述了

  • 相关阅读:
    javascript ext 闭包
    Hibernate HQL from superclass 问题
    sql查询按in顺序排序显示数据 oracle
    Hibernate createSQLquery()
    sql 分页
    javasript 闭包测试
    Excel 批量快速导入mySQL 解决方案~~
    C# 注册COM+组件步骤~
    QT错误集锦~
    QuartzNet Test~~
  • 原文地址:https://www.cnblogs.com/whocare/p/7171243.html
Copyright © 2011-2022 走看看