如何在此对象中发送上下文?

时间:2018-10-30 12:41:56

标签: javascript call bind apply

例如,我有简单的代码:

let arrayOfObjects = [{
  arrays: [arraysFunction("array object 1", "some url", () => {
    console.log(this);  // it should return {name: "array object 1", url: "some url", callback: fn}
  }])
}];


function arraysFunction(name, url, callback) {
  return {name, url, callback}
}

我希望在这里拥有我的数组对象 我怎样才能做到(应用,调用,绑定)?

2 个答案:

答案 0 :(得分:2)

要使用全部/应用,只需使用以下内容

let object = {
  arrays: [arraysFunction("array object 1", "some url", function(){
    console.log(this);
  })]
};


function arraysFunction(name, url, callback) {
  return callback.apply({name, url, callback});
}

答案 1 :(得分:1)

let object = {
  arrays: [arraysFunction("array object 1", "some url", function() {
    console.log(this);  // it should return {name: "array object 1", url: "some url", callback: fn}
  }]
};

function arraysFunction(name, url, callback) {
  callback = callback.bind({name, url, callback});
  return {name, url, callback};
}

唯一的问题是返回的回调与此回调不相同(===将不起作用)。