msff-constructor-overwrite v1.2.0
Constructor Overwrite
Overwrite a constructor function in JavaScript.
Project Status
Version 1.2.0 released in August 10, 2015 (CHANGELOG).
Travis CI:
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
- ES2015 code transpiled with tools like Babel
- Languages with class support that compile to JavaScript, like CoffeeScript and TypeScript, or one of these.
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