使用可从构造函数实例访问此方法的方法向构造函数原型添加函数

时间:2018-05-03 08:38:19

标签: javascript ecmascript-6

我希望根据以下代码中的注释获得所需的结果:

// constructor
function As(data) {
  this.data = data
}

function helloWorld() {
  console.log(this.data)
}

helloWorld.myMethod = {
  // ...do sideffect
  // desired: execute helloWorld here bound against `asI` 
}

As.prototype.helloWorld = helloWorld


const asI = new As('some data')
asI.helloWorld() // => 'some data'

// desired
asI.helloWorld.myMethod() // desired result: => 'some data'

编辑:这不是我认为的JavaScript - this of this的重复,正如下面的解决方案所证明的那样。

2 个答案:

答案 0 :(得分:1)

如果你真的需要这个属性在原型中,你可以使用自定义属性getter。



// constructor
function As(data) {
  this.data = data
}


Object.defineProperty(As.prototype, 'helloWorld', {
  get: function() {
    function helloWorld() {
      console.log(this.data)
    }
    
    helloWorld.myMethod = (function(){
      console.log(this.data)
    }).bind(this);
    
    return helloWorld;
  }
});



const asI = new As('some data')
asI.helloWorld() // => 'some data'

// desired
asI.helloWorld.myMethod() // desired result: => 'some data'




请记住,每次访问helloWorld时,这种天真的实现都会创建新功能。

答案 1 :(得分:1)

您可以使用getter和Object.assign()

// constructor
function As(data) {
  this.data = data
}

function helloWorld() {
  console.log(this.data)
}

Object.defineProperty(As.prototype, 'helloWorld', {
  get() {
    return Object.assign(helloWorld, {
      myMethod: () => {
        console.log(this.data)
      },
    })
  },
})

const asI = new As('some data')
asI.helloWorld() // => 'some data'

asI.helloWorld.myMethod() // => 'some data'