前端 函数和对象以及this 的指向问题

函数

1、首先我们要知道什么是函数?

JavaScript 函数是被设计为执行特定任务的代码块。

JavaScript 函数会在某代码调用它时被执行。

2、什么是IIFE

 立即执行函数  用于模块化的开发

 函数自调用   最好在开头写上分号  代码块的编写更加友好       

;(function fn(a){
    console.log(this)  //window
 })(2)

 //函数自调用 箭头函数

;((a,b)=>{
     console.log(a+b)
})(3,2)

//函数自调用 箭头函数

;((a,b)=> console.log(a+b))(3,2)
; ((a, b) => {
    let c = a+b
    return c
})(3, 2)

// console.log(c)  //c is not defined

; ((a, b) => {
  window.$ = () => {
   }
})(3, 2)
console.log(window.$())  //5

3、箭头函数

箭头函数怎么写

箭头函数如果参数只有一个  可以省略();如果返回值只有一句 {}也可以省略

格式 ()=>{}

对象

1、什么是对象

包含多个数据的容器,其中包含属性和方法

this

         *    总结:调用方式不同,指向不同的对象(可以简单理解:基本上是谁调用,指向谁)      

         * 直接调用函数,函数中的this永远指向window对象

         * 通过方法的形式调用函数,函数中的this指向调用方法的对象

         * 通过构造函数的形式调用函数,函数中的this指向新创建的那个对象

         * 使用call 和apply 可以改变this 的指向,this会指向新的对象

         * 如果是DOM的事件函数,this 指向的是对应的事件

     

定义一个构造函数 Person       

function Person(color) {

         console.log("1", this) //window

       this.color = color

       this.getColor = function (color) {

       console.log("2", this)

       return this.color

      }

     this.setColor = function (color) 
     console.log("3", this)
     this.color = color
}
}

Person('red');  //this 指向window  此时仅仅执行第一个console

        // let p = new Person('red')  //this 指向p,更严格应该指向Person,因为p指向Person     此时仅仅执行第一个console

        // p.getColor()  //this 指向p  Preson

        // let obj = {}

        // p.setColor.call(obj, 'black') //this 指向obj        

        // // p先调用preson 的 setColor的方法,call方法将setColor方法的this指向到obj

        // 同等于

        // obj={

        //     setColor: color => {

        //         console.log("3", this)

        //         this.color = color

        //     }

        // }

        // let test = p.setColor;

        // test();  //this 指向p  Preson

         //如果  用箭头函数  定义Person this 的指向是不一样的

        function Person(color) {

            console.log("1", this) //window

            this.color = color

            this.getColor = color => {

                console.log("2", this)

                return this.color

            }

            this.setColor = color => {

                console.log("3", this)

                this.color = color

            }

        }

        // Person('red');  //this 指向window  此时仅仅执行第一个console

        let p = new Person('red')  //this 指向p,更严格应该指向Person,因为p指向Person     此时仅仅执行第一个console

        // p.getColor()  //this 指向p  Preson

       let obj = {}

        p.setColor.call(obj, 'black') //this 指向 Preson

        let test = p.setColor;

        test();  //this 指向p  Preson


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值