访问没有`this`的对象方法

时间:2017-09-09 09:02:31

标签: javascript functional-programming

我可以在不使用this的情况下编写以下内容吗?我希望map返回另一个具有相同方法名称和方法foo的对象。如何在没有它的情况下访问对象的另一种方法?

function createSomething() {
    const foo = () => 1
    function map(f) {
        const newFoo = () => f(this.foo())
        return {
            foo: newFoo,
            map: map
        }
    }
    return {
        foo: foo,
        map: map
    }
}

const s = createSomething()
            .map( x => x+1 )
            .map( x => x*x )
            .foo()  // s === 4

2 个答案:

答案 0 :(得分:2)

在你的情况下很简单:

const newFoo = () => f(foo())

但是,您可以在每个突变中构建一个新实例并通过它传递一个状态(这将使它更容易):

function createSomething(state = 1){
  return {
    map(func){
      return createSomething(func(state));
    },
    forEach(func){
      func(state);
      return createSomething(state);
    },
    state(){ return state }
  };
}

所以你可以这样做:

 createSomething(5)
   .map( a => a +2)
   .forEach( console.log) //7
   .map( a => a + 8 )
   .forEach( console.log) //15
   .state() // 15

 const start = createSomething(5),
       second = start.map( a => a + 5),
       last = second.map(a => a + 5);

 console.log(
   start.state(),//5
   second.state(),//10
   last.state()//15
 );

答案 1 :(得分:1)

以下是您可以采取的另一种方式 - 您会在网站上看到我的其他答案中表达的这种形式



const Box = value =>
  ({
    value:
      value,
    map: f =>
      Box (f (value)),
    ap: ({value: other}) =>
      Box (value (other)),
    inspect: () =>
      `Box {${value}}`
  })

const square = x =>
  x * x

console.log (Box (3) .map (square))      // Box {3}

console.log (Box (square) .ap (Box (4))) // Box {16}




另一种方法是你可以在没有中缀式界面的情况下完成它。这里的inspect代码有点笨拙,但想法是你只留下附加到开发代码中的东西



const Box =
  {
    make: value =>
      ({ type: Box, value, inspect: Box.inspector (value) }),
    map: (f, b) =>
      Box.make (f (b.value)),
    ap: (x, f) =>
      Box.make (f.value (x.value)),
    inspector: value => () =>
      `Box {${value}}`
  }

const square = x =>
  x * x
  
console.log (Box.map (square, Box.make (3)))           // Box {3}
console.log (Box.ap (Box.make (4), Box.make (square))) // Box {16}