简体   繁体   中英

Get access to prototype context when adding a function

I would like to add a function to a prototype to add a feature to a library. How can I access to the "this" context of the prototype? I give you an example to explain what I mean.

// file a

import * as utils from './utils'
import Validation from './b'

Validation.prototype.unique = function(url, params) {
  if (!utils.isEmptyString(url) && !utils.isEmptyObject(params) {
    // make api call for testing if unique
    this._messages.push('Unique'); // <= I would like to access to "this" context of Validation in file b.
  }
  return this;
}



// file b
import * as utils from './utils'

export function Validation() {
  this._messages = [];
  this._value = undefined;
  //...
}

Validation.prototype.required = function() {
  if (!utils.isEmpty(this._value)) {
    this._messages.push('Required);
  }
  return this;
}

Your usage of this in the method works exactly like that. The only thing that needs to be fixed are the non-matching import and export statements. Either use

// file a
import Validation from './b'
…

// file b
export default function Validation() {…}

or

// file a
import { Validation } from './b'
…

// file b
export function Validation() {…}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM