Skip to content

Instantly share code, notes, and snippets.

@AndersDJohnson
Last active June 5, 2019 13:36
Show Gist options
  • Save AndersDJohnson/7458883dbc276660ca06 to your computer and use it in GitHub Desktop.
Save AndersDJohnson/7458883dbc276660ca06 to your computer and use it in GitHub Desktop.
JS constructors example
/***
* This JavaScript example demonstrates constructors and prototypes by defining a product "class".
* Written for Require.js (http://requirejs.org/) and documented with JSDoc (http://usejsdoc.org/).
*/
define('Product', [], function () {
/**
* A product type.
* @typedef Product
* @type {Object}
* @property {string} name The name of the product.
* @property {number} price The price of the product.
* @property {Object} features Features for the product.
*/
/**
* Constructor for a product.
*
* @param {Object} data A set of initial data for the product.
* @return {Product}
*/
var Product = function (data) {
this.name = data.name;
this.price = data.price;
this.features = {};
return this;
};
/**
* Set a feature selection on the product.
*
* @param key The feature key.
* @param value The feature value.
* @return {undefined}
*/
Product.prototype.setFeature = function (key, value) {
this.features[key] = value;
};
return Product;
});
/***
* Then later on, perhaps in another file, we would use it as follows:
*/
require(['Product'], function (Product) {
var macbookProduct = new Product({name: 'Macbook', price: 1199.99});
macbookProduct.setFeature('RAM', '8GB');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment