this指向

132 阅读1分钟
javascript
<button id='btn'>按钮</button>
    <script>
        //在全局作用下 this一般指向window
        //在严格模式下 this一般是undefined
        
        //在函数作用域下
        //在事件处理函数中,this一般指得是绑定事件的元素
        btn.onclick = function(){
            console.log(this);//btn
        } 

        对象调用方法时,this一般指向当前对象
        var obj = {
            name:'孙悟空',
            run :function(){
                console.log(this == obj);//true
            }
        }
        obj.run();

        在普通函数中 this一般指向window
        function fn(){
            console.log(this);//window
        }
        fn()

        在回调函数 this一般指向的也是window
        var arr = [1,2,3];
        arr.forEach((item,index)=>{
            console.log(this);//window
        })

        定时器中也为window
        setInterval(()=>{
            console.log(this);//window
        },666)

        用call的方法
        参数(新的指向,参数1,参数2);
        function fn(x,y){
            console.log(x,y,this);//1,2,'abc'
        }
        fn.call('abc',1,2)

        var obj = {
            name :'唐三',
            run : function(){
                console.log(this);//name:'唐浩',age:18
            }
        }
        var newObj = {
            name:'唐浩',
            age:18
        }
        obj.run.call(newObj)

        用apply的方法
        参数(新的指向,[参数1,参数2])
            
        function fn(x,y){
            console.log(x,y,this)
        }
        fn(1,2);
        fn.call(true,1,2);
        fn.apply(true,[1,2])

    </script>
    
    
    Vue3
    
    
    **vite+vue3.0+typescript**搭建的脚手架

```javascript
setup()函数
	我们没有必要把数据放在data里,把方法写在methods里,只需要吧数据和方法暴露出去,就可以在任何地方调用。
	ref()函数
	实现数据的双向绑定,这样就不用象vue2一样,将数据定义在data里,避免了一些不必要的双向绑定,浪费性能。

	<template>
  <div>
    {{num}}
    <div v-for="(item,index) in undoneTo" :key="index">
      <p>{{item.name}}</p>
    </div>
    <input type="text" v-model="todoList">
    <button @click="showToast">点击获取inp值</button>
  </div>
</template>
<script  lang="ts">
import { ref, reactive, defineComponent } from "vue";
//ref 取值时需要加.value
export default defineComponent({
  name: "YuButton",
  //setup函数可以代替vue2中的data,methods等,但必须加return
  setup() {
    const num = ref("10");
    console.log(num.value, "num");
    const todoList = ref("");
    const undoneTo = reactive([
      { name: "吃饭" },
      { name: "睡觉" },
      { name: "王者荣耀" }
    ]);
    //点击事件
    const showToast = () => {
      console.log(todoList.value);
    };
    return {
      showToast,
      undoneTo,
      todoList,
      num
    };
  }
});
</script>