有没有办法访问父对象?

Is there any way to access parent object?

我有如下代码,但似乎无法从 innerFn 函数访问 data 对象。有什么办法可以做到这一点吗?

export default {
 data: {
    a: "a",
    b: "b"
 },
 fn: {
    innerFn: () => console.log(data.b)
 }
}

在你的js文件中

// name the file as follows 
var func = ()=>{
 console.log("triggered your function"); 
}


export default {
 data: {
    a: "a",
    b: "b"
 },
 fn: {
    val: 3,
    innerFn: func
 }
}

现在您可以调用函数

fn.innerFn();
export default {
 data: {
    a: "a",
    b: "b"
 },
 fn: {
    innerFn: () => console.log(default.data.b)
 }

}

这可能对你有用。

为您的对象命名,然后您就不必使用 this 访问父对象 属性。

const obj = {
 data: {
    a: "a",
    b: "b"
 },
 fn: {
    innerFn: () => console.log(obj.data.b)
 }
}

export default obj

自引用是 this 关键字的用途。

使用 Object.create 您可以在范围内定义对象属性,其中 this 关键字将引用父对象。

var obj1 = Object.create(null, {
  data: {
    value: {
      a: "a",
      b: "b"
    }
  },
  fn: {
    value: function fn() {
      console.log(this.data.b);
    }
  }
});
//TEST
console.log(obj1.data.a);
obj1.fn();
//Alternative with functions
function obj2() {}
obj2.data = {
  a: "a",
  b: "b"
};
obj2.fn = function fn() {
  console.log(this.data.b);
};
console.log(obj2.data.a);
obj2.fn();

您需要使用 this 关键字。

例如:-

export default {
    data: {
        a: "World!"
    },
    methods: {
        consoleGreet: () => {
            console.log(`Hello, ${this.data.a}`)
        }
    }
}