js return的函数不会立即执行

这段代码调用errorMsg不会执行 this.$message.error(msg),为什么


 methods: {
        checkGoodForm() {
            function errorMsg(msg) {
                return function(msg) {
                    this.$message.error(msg)
                }
            }
            this.goodForm.tilte === '' && errorMsg('标题不能为空')
            this.goodForm.tilte.length < 20 && errorMsg('标题最少十个汉字')
        }
}
  methods: {
    checkGoodForm(){
      
         // 1、此处的msg是形参,调用errorMsg方法的时候需要传实参
      function errorMsg(msg){
        // 2、此处也是形参,调用return返回的方法时需要传实参
        return function (msg) {
          // 3、此处是打印的上一行调用return返回的方法时传的实参
          console.log(msg);
        }
      }
      debugger
      let check = true;
      check && errorMsg('输出了吗输出了吗')('这才是输出内容'); //前一个括号里面是针对1处的实参,后一个括号里面是针对2处的实参
    },
}

输出结果:

img

明白吗?你的写法里面缺少必要的参数,也可以说逻辑有一些问题,可以这样写,如下:

checkGoodForm(){
      // 1、此处的msg是形参,调用errorMsg方法的时候需要传实参
      function errorMsg(msg){
        // 2、此处也是形参,调用return返回的方法时需要传实参
        return (function (msg) {
          // 3、此处是打印的上一行调用return返回的方法时传的实参
          console.log(msg);
        })(msg)//此处自执行这段代码,并将errorMsg接收到的实参数据作为此方法的实参
      }
      debugger
      let check = true;
      check && errorMsg('输出了吗输出了吗'); 
    },

输出结果:

img

errorMsg(msg)是返回一个子函数,这个子函数没有调用,
你要再在errorMsg('标题不能为空')之后加.call(this)调用这个子函数
因为子函数中this指向的是 window, 要在子函数时用.call(this)传递vue对象给子函数中this

 methods: {
        checkGoodForm() {
            function errorMsg(msg) {
                return function() {//msg在外面已经传递了,这里不需要再加msg
                    this.$message.error(msg)
                }
            }
            this.goodForm.tilte === '' && errorMsg('标题不能为空').call(this)
            this.goodForm.tilte.length < 20 && errorMsg('标题最少十个汉字').call(this)
        }
}

如有帮助,请点击我的回答下方的【采纳该答案】按钮帮忙采纳下,谢谢!

img

return 的那个方法中的this不是指的vue对象吧,return 个箭头函数试试

首先按照你的要求errorMsg.call(this, "标题不能为空")可以满足,但是语句逻辑不对,为空的时候会将两个错误提示展示出来,建议改成下方两种写法之一

checkGoodForm() {
  function errorMsg(msg) {
    this.$message.error(msg);
  }
  if (!this.goodForm.tilte) return errorMsg.call(this, "标题不能为空");
  if (this.goodForm.tilte.length < 20) errorMsg.call(this, "标题最少十个汉字");
},

更常规的是箭头函数这种

checkGoodForm() {
  const errorMsg = msg => {
    this.$message.error(msg);
  }
  if (!this.goodForm.tilte) return errorMsg("标题不能为空");
  if (this.goodForm.tilte.length < 20) errorMsg("标题最少十个汉字");
},