代码之家  ›  专栏  ›  技术社区  ›  emre-ozgun

它不返回对象属性(箭头,this)

  •  0
  • emre-ozgun  · 技术社区  · 3 年前
    var std_obj = {
      activeEffect : 'fade',
      name : 'Jane',
      displayMe() {
        const doSomeEffects = () => {
          if (this.activeEffect === 'fade') { 
            console.log(this.name); // this.name have accesss and logs
            // return this.name --> gives undefined ? why can't I return?
          }
        };
        doSomeEffects();
      }
    };
    console.log(std_obj.displayMe());
    

    3 回复  |  直到 3 年前
        1
  •  3
  •   Tushar Shahi    3 年前

    this 他们的申报范围。这就是为什么 这里将指向对象。但要看到这个值,您必须像这样更改代码:

    
    var std_obj = {
      activeEffect : 'fade',
      name : 'Jane',
      displayMe() {
        const doSomeEffects = () => {
          if (this.activeEffect === 'fade') { 
            console.log(this.name); // this.name have accesss and logs
            return this.name; //uncomment this
          }
        };
        return doSomeEffects(); //if you do not use return statement, then it will by default return undefined
      }
    };
    console.log(std_obj.displayMe());
    
    

    undefined . 原因是函数默认返回 console.log("hello"); 在开发人员控制台中。这将显示hello和undefined。

    注意:如果使用函数表达式而不是箭头函数,它将返回未定义。这就是箭头功能的威力。

        2
  •  2
  •   user229044    3 年前

    你不会从这里回来的 displayMe ,你是从 doSomeEffects 显示时间 doSomeEffects() return doSomeEffects() .

      displayMe() {
        const doSomeEffects = () => {
          if (this.activeEffect === 'fade') { 
            console.log(this.name); // this.name have accesss and logs
            return this.name  // return from `doSomeEffect`
          }
        };
        return doSomeEffects(); // return from `displayMe`
      }
    
        3
  •  1
  •   rudy3091    3 年前

    我不确定但我想

    var std_obj = {
      activeEffect : 'fade',
      name : 'Jane',
      displayMe() {
        const doSomeEffects = () => {
          if (this.activeEffect === 'fade') { 
            console.log(this.name);
            return this.name
          }
        };
        return doSomeEffects();
      }
    };
    console.log(std_obj.displayMe());
    

    这就是你想做的

    doSomeEffects displayMe 显示时间

    我说得对吗?