Overriding toString method - public/private access - javascript

I have a basic library I created as follows:
(function () {
function Store() {
var store = [];
if (!(this instanceof Store)) {
return new Store();
}
this.add = function (name, price) {
store.push(new StoreItem(name, price));
return this;
};
}
function StoreItem(name, price) {
if (!(this instanceof StoreItem)) {
return new StoreItem();
}
this.Name = name || 'Default item';
this.Price = price || 0.0;
}
Store.prototype.toString = function () {
// build a formatted string here
};
StoreItem.prototype.toString = function () {
return this.Name + ' $' + this.Price;
};
window.shop = window.shop || {
Store: function () {
return new Store();
}
};
}());
The large majority of this works well! However, I do not want to expose my store array defined in the Store constructor as I do not want it modified in anyway outside this library's control.
But, on the contrary, I would like to override the Store's toString method to make use of the StoreItems in the store array so I can return a formatted string of all the StoreItems using its toString method.
E.g. if store was exposed, the toString method would look something like:
Store.prototype.toString = function () {
return this.store.join('\r\n');
};
// shop.Store().add('Bread', 2).add('Milk', 1.5).toString() result:
// Bread $2
// Milk $1.5
Is there anyway I can achieve this without exposing my store array publicly?

You can give each Store it's own .toString method, being privileged to access the local store variable through closure - just like you did with .add:
function Store() {
if (!(this instanceof Store)) {
return new Store();
}
var store = [];
this.add = function(name, price) {
store.push(new StoreItem(name, price));
return this;
};
this.toString = function () {
return store.join('\n');
};
}
Alternatively, you will have to define some kind of accessor method anyway, or your store would be useless if you only can add to it but never read it. Something will need to display the store items, will need to iterate them, will need to test them for availability… If you create a generic accessor, maybe in form of some iterator (an each method with a callback?), then a .prototype.toString method could use that as well.

It's possible to keep the prototype toString method whilst protecting store, by adding a public method that returns the stringified store, and calling it from Store.prototype.toString.
Below I added this.getStoreString to the constructor, and called it from the original toString.
(function () {
function Store() {
var store = [];
if (!(this instanceof Store)) {
return new Store();
}
this.add = function (name, price) {
store.push(new StoreItem(name, price));
return this;
};
// new method
this.getStoreString = function(){
return store.join('\r\n');
};
}
function StoreItem(name, price) {
if (!(this instanceof StoreItem)) {
return new StoreItem();
}
this.Name = name || 'Default item';
this.Price = price || 0.0;
}
Store.prototype.toString = function () {
// call the new method
return this.getStoreString();
};
StoreItem.prototype.toString = function () {
return this.Name + ' $' + this.Price;
};
window.shop = window.shop || {
Store: function () {
return new Store();
}
};
}());
Fiddle
#Bergi's answer seems simpler though, but this shows another option.

Related

prototypal inheritance & how to do a super()

I'm trying to understand how to create inheritance. I think I have it (below), but the part I can't figure out is how to call the "baseclass" method (ie, doing a "super()"). How do I call the delegate's talk() method below?
(demo link: https://plnkr.co/edit/H76NFBiuWqgaZaUfR7H2?p=preview)
function Person(name) {
var api = {
name,
talk
}
return api;
function init(name) {
this.name = name;
}
function talk() {
return (`I am ${this.name}`)
}
}
function Student(name, major) {
var api = {
major: major,
talk
};
var o = $.extend({}, Person(name), api);
return o;
function changeMajor(newMajor) {
this.major = newMajor;
}
function talk() {
var str = ""
// var str = Person.prototype.talk.call(this)
str += ` and I study ${major}`;
return str;
}
}
var s = Student("Sue", "Economics")
console.log(s.talk())
You lose the reference to the "super" talk method from the Person object when using extend:
var o = $.extend({}, Person(name), api);
Although that parent object is created, it is not stored. Only the modified version of it (with api.talk overriding its talk method) is available in o.
So... you need to keep a reference to the original talk method:
var proto = Person(name);
var o = $.extend({}, proto, api);
And then reference it:
var str = proto.talk.call(this);
Note that since ES6 you can use the native Object.assign which has similar functionality as $.extend.
function Person(name) {
var api = {
name,
talk
};
return api;
function init(name) {
this.name = name;
}
function talk() {
return (`I am ${this.name}`)
}
}
function Student(name, major) {
var api = {
major: major,
talk
};
var proto = Person(name);
var o = Object.assign({}, proto, api);
return o;
function changeMajor(newMajor) {
this.major = newMajor;
}
function talk() {
var str = proto.talk.call(this);
str += ` and I study ${major}`;
return str;
}
}
var s = Student("Sue", "Economics");
console.log(s.talk());
You could reveal the init method in your api objects but mark it as I'm not part of the published API, I only happen to be public here so to say. Leveraging a naming convention you could do something like this:
function Person(name) {
var api = {
"__init__": function () {
// I'm part of the API but please treat me as private
},
talk: function () {
// Do sth.
}
};
return api;
}
function Student(name, major) {
var personApi = Person(name);
var api = {
"__init__": function () {
// I'm also part of the API but treat me as private
personApi.__init__.call(this, name)
},
talk: function () {
return personApi.talk.call(this);
}
};
return api;
}
But then you'd have to marshall around the this and you have to think about not accidentally overriding you __init__ so you customize your own $.extend() function... the rabbit hole goes deep :-). Things like this have been done by some frameworks in the past but I personally wouldn't recommend rolling your own object system - it's fun as a toy but in this day and age there are better options.
The old ES5 way to do this is via constructor functions:
// Base `class` is just a constructor function
function Person(name) {
this.name = name;
}
Person.prototype.talk = function () {
// Do sth.
};
function Student(name, major) {
Person.call(this, name); // emulating super(name)
}
Student.prototype = Object.create(Person.prototype);
Student.prototype.changeMajor = function () {
// Do sth.
};
// later
var homer = new Student("Homer Simpson", "Donuts");
In modern browsers or with the help of a transpiler say babeljs or TypeScript you can do this - which is probably what you wanted in the first place:
class Person {
constructor(name) {
this.name = name;
}
talk() {
// Do sth.
}
}
class Student extends Person {
constructor(name, major) {
super(name); // proper super(name);
this.major = major; // Or anything you want to do
}
changeMajor() {
// Do sth.
super.talk();
}
}
// later
let homer = new Student("Homer Simpson", "Donuts");

Javascript ,classes to add constructor-function

I'm kinda new with js + ES6 + class; I have problem with creating function inside constructor.
#1. I need to add new Hobby, a person allowed to have plenty hobbies ;
#2. I don't know how to show all the data of students;
another questions are in the comments ,in case if you want to answer it too, if not i'm also fine.
so here's my code :
class Student {
constructor(name,hobbies){
this.name = name;
var hobby = new Set(); //do I set here or inside the function ??
//since the function addHobbies also need, then it's fine to be global right ?
this.hobbies = (hobbies) => { //function ES6 like this right ??
this.hobbies = hobby.add(hobbies);
return this.hobbies; //can I return hobby instead of this.hobbies ??
};
}
setName(newName){
this.name = newName;
}
addHobbies(newHobbies){
this.Hobbies = hobby.add(newHobbies); //it should be like this to add >> to set ?
}
getName(){
return this.name;
}
getHobbies(){
return this.hobbies;
}
}
and how to return all the data ?
let andy = new Student("andy","dance");
let vince = new Student("vince","codding");
so it will show all students-attribute by getCode() ?
do I set here or inside the function ??
That depends on what you need. Do you want each Student instead to have one set of hobbies, or do you want to create a new set every time the function is called?
this.hobbies = (hobbies) => { //function ES6 like this right ??
this.hobbies = hobby.add(hobbies);
That doesn't work at all. You're creating the property with a function value, but when the method is called you're overwriting the property with the return value of the add method.
To make it work, I'd recommend making the .hobbies set an instance property instead of a local variable.
class Student {
constructor(name, ...hobbies) {
this.name = name;
this.hobbies = new Set();
this.addHobbies(...hobbies);
}
getName() {
return this.name;
}
setName(newName) {
this.name = newName;
}
getHobbies() {
return this.hobbies;
}
addHobbies(...newHobbies) {
for (const newHobby of newHobbies)
this.hobbies.add(newHobby);
}
}
Alternatively, if you insist on using a local constructor variable, it would look like this:
class Student {
constructor(name, ...hobbies) {
this.name = name;
this.hobbies = new Set(...hobbies);
this.getHobbies = () => {
return this.hobbies;
};
this.addHobbies = (...newHobbies) => {
for (const newHobby of newHobbies)
this.hobbies.add(newHobby);
};
}
… // further methods (for name etc)
}
Try this:
class Student {
constructor(name, hobbies) {
this.name = name;
// Allow passing both an array of hobbies and a single hobby
this.hobbies = Array.isArray(hobbies) ? new Set(hobbies) : new Set([hobbies]);
}
setName(newName) {
this.name = newName;
}
addHobbies(newHobbies) {
if (Array.isArray(newHobbies)) {
newHobbies.forEach((hobby) => this.hobbies.add(hobby));
} else {
this.hobbies.add(newHobbies);
}
}
getName() {
return this.name;
}
getHobbies() {
return this.hobbies;
}
}
let andy = new Student("andy","dancing");
let vince = new Student("vince",["codding", "running"]);
andy.addHobbies("slipping");
vince.addHobbies(["running", "eating"]);
You are in the correct direction. I have rewritten your class to do what I think is more similar to what you are trying to achieve.
Play with the code at: https://jsbin.com/vejumo/edit?js,console
And here's the rewritten class:
class Student {
constructor(name, hobbies = []){
this.name = name;
// new Set() is used to work with objects. It does not work with well with strings
// Let's use an array to store the hobbies.
// if a hobby or an hobbies array is passed, store it, otherwise set an empty array.
this.hobbies = this.parseHobbies(hobbies);
}
// This function will normalize the hobbies to an Array
parseHobbies(hobbies) {
if (typeof hobbies === "string") {
// hobbies is a string, means it's a single hobby and not an array
return [hobbies];
}
// Assuming the hobbies is a an Array
return hobbies;
}
setName(newName) {
this.name = newName;
}
// this function will allow you to add a single hobby to the array
addHobbies(hobbies = []) {
// Same logic like in constract, this can accept a string or an array
// We use Array.concat and push to append to array
this.hobbies = this.hobbies.concat(this.parseHobbies(hobbies));
}
getName() {
return this.name;
}
getHobbies() {
return this.hobbies
}
// This will return all student attributes.
getAttributes() {
// Return a copy of all the attributes instead of returning references
return Object.assign({}, this);
}
}
let george = new Student("George", "Sports");
george.addHobbies(["Singing", "Fishing"]);
george.addHobbies("Dancing");
console.log(george.getAttributes());

How to properly derive object with private vars using javascript (prototypal) inheritance

I am new to JavaScript's (prototypal) inheritance and I'm trying to learn more about it.
I am using a simple observer pattern as example, in which I want observable objects to be derived from the 'subject' object. This is what I WANT to do:
function subject()
{
var callbacks = {}
this.register = function(name, callback)
{
callbacks[name] = callback;
}
this.unregister = function(name)
{
delete callbacks[name];
}
var trigger = function()
{
var a = arguments;
var t = this;
$.each(callbacks, function(name, callback)
{
callback.apply(t, a);
});
}
}
list.prototype = new subject()
function list()
{
var items = {}
this.add = function(name, item)
{
items[name] = item;
trigger('add', name);
}
this.remove = function(name)
{
delete items[name];
trigger('remove', name);
}
}
Now when using the code above like below, I run into my first problem:
var l = new list()
l.register('observer1', function() { console.log(this, arguments) });
l.add('item1', 'value1'); // <-- ReferenceError: trigger is not defined, trigger('add', name);
To continue testing I made the trigger function 'public' using this.trigger instead. Running my example again I run into the next problem:
var l = new list()
l.register('observer1', function() { console.log(this, arguments) });
l.add('item1', 'value1'); // <-- output: subject, ["add", "item1"]
The this object is subject, I want it to be list. My third problem occurs when creating another list:
var l2 = new list();
//Don;t register any observers
l2.add('item1', 'value1'); // <-- output: subject, ["add", "item1"]
The callbacks list is shared between the 2 lists.
I've tried similar things with Object.create(new subject()) as well and run into similar problems.
My 3 questions in this are:
Can I have private methods that can be used in derived objects (and
should I even care about having them private or public)?
How can I have the this object I want (without needing to use function.call in the derived object, if possible)?
How can I keep the callbacks list in the base object without it being shared?
An interesting question. As for #1 and #2: let's say you have a function foo:
function foo() {
var _private = 'private var!';
this.access = function () {
return _private;
}
}
access is a so-called privileged method, it's a closure that can access the private variable private.
you can inherit the whole thing by making use of call, like so:
function bar() {
foo.call(this);
}
var b = new bar();
console.log(b.output()); // prints 'private var!'
With the methods apply, call and bind you can establish the context of a function, effectively tamper with the this object. (your #2 question, read here )
Naturally you cannot make use of a totally private method in a derived object. You'd need an accessor method which would defeat the purpose of the original method being private. Having said that, that's the way it works in strongly typed languages too (in java if you mark a method as private not even subclases will be able to access it, it would have to be protected).
As for #3, I cannot think of how to keep callbacks shared and private.
But you can make it a static property for all instances of a function (much like a static property in a lanaguage like java) by simply declaring a function like:
function foo() {
}
add your prototypes which will be assigned to each instance
foo.prototype.bar = // ...
and a static property
foo.callbacks = [];
All instances of foo will share the callbacks property.
You can’t have private methods, and that’s that. It will never work both properly and nicely at the same time, so don’t bother trying to emulate them in JavaScript.
Then all you have to do is call the parent’s constructor in the derived constructor.
function subject()
{
var callbacks = {};
this.register = function(name, callback)
{
callbacks[name] = callback;
};
this.unregister = function(name)
{
delete callbacks[name];
};
this.trigger = function()
{
var a = arguments;
var t = this;
$.each(callbacks, function(name, callback)
{
callback.apply(t, a);
});
};
}
list.prototype = Object.create(subject);
list.prototype.constructor = list;
function list()
{
subject.call(this);
var items = {};
this.add = function(name, item)
{
items[name] = item;
this.trigger('add', name);
};
this.remove = function(name)
{
delete items[name];
this.trigger('remove', name);
};
}
Incorporating Joe's suggestion, this is what I eventually ended up with:
function subject()
{
var callbacks = {}
this.register = function(name, callback)
{
callbacks[name] = callback;
}
this.unregister = function(name)
{
delete callbacks[name];
}
trigger = function()
{
var a = arguments;
var t = this;
$.each(callbacks, function(name, callback)
{
callback.apply(t, a);
});
}
}
//without the following line, 'this' in firefox is 'subject' instead of 'list' (in chrome it is)
list.prototype = new subject()
//without these, 'list' is not an instanceof 'subject'
list.constructor = subject;
list.prototype.constructor = list;
function list(n)
{
this.name = n;
subject.call(this); //as suggested by Joe
var items = {}
this.add = function(name, item)
{
items[name] = item;
trigger.call(this, 'add', name); //no way to do this without using call/apply
}
this.remove = function(name)
{
delete items[name];
trigger.call(this, 'remove', name); //no way to do this without using call/apply
}
this.getitems = function() { return items }
}
//without the following line, 'this' in firefox is 'subject' instead of 'queue'
queue.prototype = new subject()
//without these, 'queue' is not an instanceof 'subject'
queue.constructor = subject;
queue.prototype.constructor = queue;
function queue(n)
{
this.name = n;
subject.call(this); //as suggested by Joe
var items = [];
this.enqueue = function(item)
{
items.push(item);
trigger.call(this, 'enqueue', item); //no way to do this without using call/apply
}
this.dequeue = function()
{
var d = items.shift();
trigger.call(this, 'dequeue', d); //no way to do this without using call/apply
return d;
}
this.getitems = function() { return items }
}
var l1 = new list('l1')
l1.register('observer1', function() { console.log('l1', this, arguments) });
l1.add('item1', 'value1');
// ^ 'l1', list { name = 'l1' ... }, ['add', 'item1']
var l2 = new list('l2')
l2.register('observer2', function() { console.log('l2', this, arguments) });
l2.add('item2', 'value2');
// ^ 'l2', list { name = 'l2' ... }, ['add', 'item2']
var q1 = new queue('q1')
q1.register('observer3', function() { console.log('q1', this, arguments) });
q1.enqueue('item3');
// ^ 'q1', queue { name = 'q1' ... }, ['enqueue', 'item3']
console.log(l1 instanceof list, l1 instanceof subject, l1 instanceof queue);
// ^ true, true, false
console.log(q1 instanceof list, q1 instanceof subject, q1 instanceof queue);
// ^ false, true, true
This ticks all of my boxes (except for the use of call, but I can live with that).
Thanks for all the help,
Mattie
EDIT: appearantly this does not work as expected. creating a new object overwrites the other objects callbacks

Passing arguments to anonymous function of module

$(document).ready(function () {
var patient = (function (options) {
var age = options.age;
var name = options.name;
function getName() {
return this.name;
}
function setName(val) {
name = val;
}
function getAge() {
return this.age;
}
function setAge(val) {
age = val;
}
return {
getAge: getAge,
setAge: setAge,
getName: getName,
setName: setName
}
})();
});
I realize that I'm never passing any options in my example here.
If I try to do something like patient.setAge('100') and then console.log(patient.getAge()) I get an error saying cannot read property Age of undefined. The overarching theme that I'm trying to get at is within a module, how can I emulate consturctors to instantiate a new patient object while keeping all the OOP goodness of private variables and all that jazz.
I've seen some examples of constructors in a module pattern on here and I haven't understood them very well. Is it a good idea in general to have a constructor in a module? Is its main purpose similarity with class-based languages?
This is a constructor:
function Patient(options) {
options = options || {};
this.age = options.age;
this.name = options.name;
}
$(document).ready(function () {
var patient = new Patient();
});
You can put it inside a module if you want. What you shouldn’t do is provide getters and setters, especially ones that don’t do anything. If you’re exposing a variable through two properties to get and set it, it should just be one property.
Try this
function Patient (options) {
options = options || {};
var age = options.age;
var name = options.name;
function getName() {
return name;
}
function setName(val) {
name = val;
}
function getAge() {
return age;
}
function setAge(val) {
age = val;
}
return {
getAge: getAge,
setAge: setAge,
getName: getName,
setName: setName
}
}); // pass empty object
$(document).ready(function () {
var p1 = new Patient({});
var p2 = new Patient();
var p3 = new Patient({age:20});
var p4 = new Patient({name:"abcd"});
var p5 = new Patient({age:21, name:"abcd"});
});

automatic getter and setter(with validation) in javascript

I am building a javascript library where I have to create a log of classes and most of them have a lot of properties which have to make public for the user.
For example:
function Person(name,age){
}
Now I want to create the getter and setter for properties (name and age).
Nornall, I have to add these methods to Person.prototype:
Person.prototype.getName=function(){}
Person.prototype.setName=function(x){
//check if x is typeof String
}
Person.prototype.getAge=function(){}
Person.prototype.setAge=function(x){
//check if x is typeof Number
}
This will result in two many lines of repeated codes.
So I wonder if I can call a method like this:
makeThesePropertiesPublic(Person,{
name:"string",
age:"number"
});
Then I can call this:
var p=new Person("xx",1);
p.getName();
p.getAge();
.......
Is there a out-of-box method to implement this?
First of all you can't define the getter and setter functions on the prototype because they need to be able to access name and age which are only accessible inside the constructor. Hence you would need to define the getter and setter functions inside the constructor.
I would do this:
function Person(name, age) {
var private = {
name: name,
age: age
};
Object.defineProperties(this, {
name: getAccessor(private, "name", "String"),
age: getAccessor(private, "age", "Number")
});
}
function getAccessor(obj, key, type) {
return {
enumerable: true,
configurable: true,
get: function () {
return obj[key];
},
set: function (value) {
if (typeOf(value) === type)
obj[key] = value;
}
};
}
function typeOf(value) {
return Object.prototype.toString.call(value).slice(8, -1);
}
Now you can access create a Person and access their name and age properties as follows:
var person = new Person("Aadit M Shah", 20);
person.name = 0; // it won't set the name
person.age = "twenty"; // it won't set the age
alert(person.name);
alert(person.age);
See the demo: http://jsfiddle.net/aVM2J/
What about something like this?
function Person(n, a) {
var name = n;
var age = a;
var person = {};
person.getName = function () {
return name
}
person.getAge = function () {
return age;
}
return person;
}
var p = Person("jon",22);
console.log(p.getName());//jon

Categories