1.2.0 • Published 9 years ago

msff-constructor-overwrite v1.2.0

Weekly downloads
1
License
MIT
Repository
github
Last release
9 years ago

Constructor Overwrite

Overwrite a constructor function in JavaScript.

Project Status

Version 1.2.0 released in August 10, 2015 (CHANGELOG).

Travis CI:

  • New features: Build Status
  • Stable version: Build Status

What this project is for?

This project is recommended to extend or rewrite constructor functions in javascript using a lightweight code.

What this project is not for?

This project is not recommended to give class inheritance feature to ES5/ES3 projects. In this case, we recommend to use

Install

This project is available as npm package:

npm install --save msff-constructor-overwrite

If you're using TypeScript, you must also link the definitions files with TSD:

tsd link

Usage

var overwrite = require('msff-constructor-overwrite');
// overwrite(oldConstructor, newConstructor);
// overwrite(oldConstructor, newConstructor, propertyForOldConstructor);

The newConstructor will receive the prototype of oldConstructor. If newConstructor already have a prototype, it'll be overwritten.

In addition, newConstructor will have the old constructor stored in a static property named ___oldConstructor. You can use a custom name by using the third argument.

Overwriting constructor

var overwrite = require('msff-constructor-overwrite');

var Person = (function() {
  function Person(name) {
    this.name = name;
  }

  return Person;
})()

Person = overwrite(Person, function(firstName, lastName) {
  this.name = [firstName, lastName].join(" ");
});

var me = new Person('Marcos', 'Filho')
// me.name => Marcos Filho

Extending constructor

var overwrite = require('msff-constructor-overwrite');

var Person = (function() {
  function Person(name) {
    this.name = name;
  }

  return Person;
})()

Person = overwrite(
  Person,
  // You must name the constructor to extend
  function Person_Extended(firstName, lastName) {
    this.fullName = [firstName, lastName].join(" ");

    // Calling the old constructor
    Person_Extended.old.apply(this, arguments)
  },
  // By default the old goes on `___oldConstructor`
  // Use the third parameter to overwrite the property
  "old"
);

var me = new Person('Marcos', 'Filho')
// me.name => Marcos
// me.fullName => Marcos Filho