javascript函数

函数补充

  • 自调用函数

          函数定义和调用写在一块
          (function(){
              // 函数体
          })()
    
  • 作用:
    封装代码
    封装私有变量,独立于全局变量

  • arguments 对象
    - => 函数所有实参的集合
    - => 函数体中直接使用
    - => 类数组形式存在
    - => 函数可变参数,动态传参

// 计算任意数总和
        function sum(){
            var s = 0 
            for(var i = 0; i < arguments.length; i++){
                s = s + arguments[i]
            }
            return s
        }
        var s =  sum(10,20,30,50)
        alert(s)

this关键字

this表示当前对象;在同场景下this表示不同的对象

	  1. 事件处理函数中的this
	                 this->事件源
       2. 普通函数中this
            this -> window对象
       3. 定时器中this
            this -> window对象
       4. 自调用函数中this
            this -> window对象
       5. 对象方法中的this    调用该方法的引用变量指向的对象
            Object
            var obj = {
                name:'jack',
                say:function(){
                    console.log( '对象Object方法中this->' ,this); //obj 对象
                }
            }
            obj.say()
<body>
		<button>确定</button>
		<script>
			function test1() {
				var btn = document.querySelector('button')
				btn.addEventListener('click', function () {
					// this->事件源->button按钮
					console.log('this : ', this)
				})
			}

            function fun(){
                console.log('this -> ',this) //指向window对象
            }
            fun()

           setTimeout(function(){
               console.log('定时器 this -> ',this) //指向window对象
            },1000)

           (function(){
                 console.log('自调用函数this -> ',this)//指向window对象 
             })()
             
            var obj = {
                name:'jack',
                say: function(){
                   console.log(this.name + '说话, say方法调用'); //jack
                   console.log('对象Object方法中this -> ',this) //
                }
            }

            obj.say()

		</script>
	</body>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值