Добавьте функцию к прототипу конструктора с помощью метода с доступом к нему из экземпляра конструктора - PullRequest
0 голосов
/ 03 мая 2018

Я хотел бы получить желаемый результат в соответствии с комментариями в коде ниже:

// 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 - это этого , как я думал, о чем свидетельствуют приведенные ниже решения.

Ответы [ 2 ]

0 голосов
/ 03 мая 2018

Вы можете использовать геттер вместе с 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'
0 голосов
/ 03 мая 2018

Если вам действительно нужно, чтобы это свойство было в прототипе, вы можете использовать пользовательское свойство 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.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...