0
点赞
收藏
分享

微信扫一扫

Vue3 插槽用法详解

双井暮色 2024-08-13 阅读 35

this

  • this的5种绑定方式
  1. 默认绑定(非严格模式下this指向全局,严格模式下函数内的this指向undefined)
  2. 隐式绑定(当函数引用有上下文对象,如obj.foo()的调用方式,foo内的this指向obj)
  3. 显式绑定(通过call或者apply方法直接指定this的绑定对象)
  4. new构造函数绑定,this指向新生成的对象
  5. 箭头函数,this指向的是定义时所在上下文的this值,箭头函数的this在定义时就决定了,不能改变
"use strict";
var a = 10; // var定义的a变量挂载到window对象上
function foo () {
  console.log('this1', this)  // undefined
  console.log(window.a)  // 10
  console.log(this.a)  //  报错,Uncaught TypeError: Cannot read properties of undefined (reading 'a')
}
console.log('this2', this)  // window
foo();

var obj2 = {
  a: 2,
  foo1: function () {
    console.log(this.a) // 2
  },
  foo2: function () {
    setTimeout(function () {
      console.log(this) // window 
      console.log(this.a) // 3
    }, 0)
  }
}
var a = 3

obj2.foo1()
obj2.foo2() 

var obj = {
 name: 'obj',
 foo1: () => {
   console.log(this.name) // window
 },
 foo2: function () {
   console.log(this.name) // obj
   return () => {
     console.log(this.name) // obj
   }
 }
}
var name = 'window'
obj.foo1()
obj.foo2()()


举报

相关推荐

Vue3插槽

Vue3 - 插槽 Slots

vue3 插槽 slot 使用

Vue3(5)插槽Slots

Vue3详解

vue插槽详解

0 条评论