zoukankan      html  css  js  c++  java
  • this指向

    this指向

    //this在函数定义的时候 确定不了,执行的时候才能确定指向
    //最终指向的是调用它的对象(指向最近的调用)
    定时器/全局/事件回调/匿名函数/对象属性/箭头函数
    window/window/事件对象/window/调用者/定义它的上下文this
    
    • 普通函数调用
    // this指向window
     function fn() {
                console.log(this) //window
            }
    
    • 对象属性调用
     var o = {
                user: "zs",
                fn: function () {
                    console.log(this.user)
                }
            }
            o.fn() //zs
            var result = o.fn  //全局函数
            result() //undefined
    

    new操作符做了哪些工作

    创建一个对象
    为这个对象绑定原型
    执行构造函数代码
    返回新对象
    
    • 构造函数this
     function Fn() {
                this.user = "zs"
            }
            var a = new Fn()
            console.log(a.user) //zs
    // a仅仅是创建的实例对象 没有执行
    
    • return和this
     function fn() {
                this.user = "zs"
                return {}
            }
            var o = new fn()
            console.log(o.user) //undefined
        function fn() {
                this.user = "zs"
                return function () { }
            }
            var o = new fn()
            console.log(o.user) //undefined
        function fn() {
                this.user = "zs"
                return 1  //   undefiend / null
            }
            var o = new fn()
            console.log(o.user) //"zs"
    // 如果返回值是一个对象,那么this指向的就是那个返回的对象,如果返回值不是一个对象那么this还是指向函数的实例。
    

    参考:https://www.cnblogs.com/pssp/p/5216085.html

  • 相关阅读:
    React组件的Refs
    Typechecking With PropTypes
    酷炫Jquery收集
    JSTL函数标签库 fn标签学习
    Struts标签 比较时间大小
    Struts2 拦截器 配置IFrame页面跳转
    实体Bean, Entity 注解设置
    Uploadify 参数说明
    Uploadify jsp使用示例
    百度umeditor
  • 原文地址:https://www.cnblogs.com/rainbowqq/p/13267135.html
Copyright © 2011-2022 走看看