2017-10-19 71 views
0

我有这个函数func,它总是被调用为func.bind(this)。对于func,隐含地假定该函数的上下文始终是调用者的上下文this。这似乎有点重复,并且像这样调用func显然可能导致误用,因为一些用户可能很容易忘记调用func而不将其绑定到this。我想知道是否有一个简洁的方式总是使用其调用者的this上下文。有没有一个Javascript函数`func`被称为`func.bind(this)`

我正在考虑使用强制用户输入调用者上下文的高阶方法。该方法将如下所示:

function createFunc(context) { 
    return function func() { 
    // rather than call `this`, you use the input parameter, `context`. 
    } 
} 
+0

这两个工作。使用ES6的新的'()=> {}'语法来定义函数会隐式地将'this'绑定到调用者的'this'。 – Shadow

+0

'将隐式绑定到调用者的这个' - 这听起来不太正确 –

+0

我不认为我理解你的问题/问题。你能提供一个具体的例子吗? *“我想知道是否有一种简洁的方式来始终使用其调用者的这种上下文。”*否。调用者必须在通话时明确设置“this”。 –

回答

0

可以使用其他参数来创建它期望的函数功能,对象设置上下文this,和N参数和Reflect.apply()设置this在函数调用

// default `this` object 
 
const o = { 
 
    n: 10 
 
}; 
 
// `func` : function to pass as first parameter to `fn` 
 
// `THIS` : object to set to `this` within `fn`, if `undefined` use `o` 
 
// `args` : N arguments to `func` 
 
const fn = function fn(func, THIS = o, ...args) { 
 
    return Reflect.apply(func, THIS, args) 
 
} 
 

 
let res = fn(
 
      function func(...params) { 
 
       // do stuff 
 
       return params.map(n => this.n * n * Math.PI) 
 
      } 
 
      , void 0 
 
      , 10, 20, 30, 40, 50 
 
     ); 
 

 
console.log(JSON.stringify(res, null, 2));

2

我在想,如果有一个送花儿给人简洁的方式s使用其调用者的this上下文。

你基本上似乎是要求动态范围。 this如何获得其价值的方式是动态的,但大多数情况下它是显式。您似乎需要一个函数,它隐式地将其调用作用域的值设为this

这在JavaScript中不可行。来电者必须通过f.call(this)f.apply(this)明确设置this的值。