JavaScript prototypal inheritance: succinct syntax? - javascript

Is there a more succinct way to express this than three distinct, procedural operations? Something more object notation-like, or at least all within the body of the Name function?
Problem:
function Name(first, last) {
this.first = first;
this.last = last;
}
Name.prototype = new String;
Name.prototype.toString = function() {
return this.last + ', ' + this.first;
};
Test:
console.log(new Name("jimmy", "dean").toString())
console.log(new Name() instanceof Name);
console.log(new Name() instanceof String);
console.log(new Name() instanceof Object);
console.log(Name.prototype.toString.call(new Name('jimmy', 'dean')));
console.log(Name.prototype.toString.call({
first: 'jimmy',
last: 'dean'
}));
Expected output:
< "dean, jimmy"
< true
< true
< true
< "dean, jimmy"
< "dean, jimmy"

Example
function Name(first, last) {
this.partFirst = first;
this.partLast = last;
this.valueOf = this.toString = function() {
return this.partLast + ', ' + this.partFirst;
}
}
Name.prototype = new String();

Here's how I do it:
function subclass(constructor, superConstructor) {
function surrogateConstructor() { }
surrogateConstructor.prototype = superConstructor.prototype;
var prototypeObject = new surrogateConstructor();
prototypeObject.constructor = constructor;
constructor.prototype = prototypeObject;
}
/* Base object */
function BaseItem() {
this.type = 'baseitem';
this.obj = null;
}
BaseItem.prototype.render = function() {
return "foo";
}
/* Sub class */
function InteractionArea() {
BaseItem.call(this);
this.type = 'interactionarea'
this.obj = document.createElement('div')
}
subclass(InteractionArea, BaseItem);
//here come the overrides
InteractionArea.prototype.render = function() {
return "foobar";
}
InteractionArea.prototype.render2 = function() {
return "foobar";
}
/* Sub-sub class */
function InteractionArea2() {
InteractionArea.call(this);
this.type = 'interactionarea2';
this.obj = false;
}
subclass(InteractionArea2, InteractionArea);
InteractionArea2.prototype.render = function() {
return "bar";
}

Sure. Use Object.create.
var Name = Object.create(String.prototype, {
toString: { value: function _toString() {
return this.partLast + ', ' + this.partFirst;
} },
constructor: { value: function _constructor(first, last) {
this.partFirst = first;
this.partLast = last;
return this;
} }
});
var name = Object.create(Name).constructor("foo", "bar");
Now ES5 is a bit ugly, so you can use some mechanism for ES5 OO sugar, let's take pd as an example:
var Name = pd.make(String.prototype, {
toString: function _toString() {
return this.partLast + ', ' + this.partFirst;
},
constructor: function (first, last) {
this.partFirst = first;
this.partLast = last;
},
beget: pd.Base.beget
});
console.log(Name.beget("jimmy", "dean").toString())
console.log(Name.isPrototypeOf(Name.beget()));
console.log(String.prototype.isPrototypeOf(Name.beget()));
console.log(Object.prototype.isPrototypeOf(Name.beget()));
console.log(Name.toString.call(Name.beget('jimmy', 'dean')));
console.log(Name.toString.call({
partFirst: 'jimmy',
partLast: 'dean'
}));
Of course output is as expected Live Example

Related

can't use filter function on array

I learn how to code in javascript. I have always error: "Cannot read property 'filter' of undefined". What am I doing wrong here and why?
I have to build A class with Singleton pattern and B class which will be observer of A class.
I have to add some instances of B class to A as subscribers (observers) and unsubscribe any of it when random value I from A class is bigger than random value P from B class.
var A = (function()
{
// Instance stores a reference to the Singleton
var instance;
function init() {
// Singleton
var i = 0;
let observers = new Array();
function CheckIfGreaterThanI(observer)
{
console.log("CHECKING");
return observer.getP() > this.getI();
}
return {
subscribe: function(observer)
{
console.log("DODAJĘ");
observers.push(observer);
},
unsubscribe: function(observerss)
{
console.log("USUWAM");
for(i=0;i<observerss.length;i++)
{
var index = this.observers.indexOf(observerss[i])
if (~index)
{
this.observers.splice(index, 1);
}
}
},
notify: function()
{
for(let observer of observers)
{
observer.update();
}
},
getI: function()
{
return this.i;
},
setI: function(value)
{
this.i = value;
this.notify();
///THAT'S THE PLACE WHERE ERROR RISES
var observersToUnsubscribe = this.observers.filter(this.CheckIfGreaterThanI);
this.unsubscribe(observersToUnsubscribe);
}
};
};
return
{
// Get the Singleton instance if one exists
// or create one if it doesn't
getInstance: function () {
if ( !instance ) {
instance = init();
}
return instance;
}
};
})();
function B (name,value,a) //observer
{
this.Name = name;
this.P = value;
this.A = a;
}
B.prototype =
{
constructor:B,
getName : function()
{
return this.Name;
},
getP : function()
{
return this.P;
},
update : function()
{
if(A.getInstance().getI()<this.P)
{
console.log("OK - " + this.Name);
}
}
};
for(i=0;i<10;i++)
{
var bObject = new B(i,Math.random(),A.getInstance());
A.getInstance().subscribe(bObject);
}
var ChangeIValue = function()
{
A.getInstance().setI(Math.random());
}
setTimeout(function run()
{
ChangeIValue();
setTimeout(run,1000);
}
, 1000);
OK, I resolved this problem alone and there were many mistakes behind it, so I added my solution for that:
var A = (function()
{
// Instance stores a reference to the Singleton
var instance;
function init() {
// Singleton
var i = 0;
var observers =[];
function CheckIfGreaterThanI(observer)
{
return observer.getP() > i;
}
return {
subscribe: function(observer)
{
observers.push(observer);
},
unsubscribe: function(observersToUnsubscribe)
{
for(let observer of observersToUnsubscribe)
{
var index = observers.indexOf(observer);
if(index!=-1)
{
observers.splice(index,1);
}
}
},
notify: function()
{
for(let observer of observers)
{
observer.update();
}
},
getI: function()
{
return i;
},
setI: function(value)
{
i = value;
this.notify();
var observersToUnsubscribe = observers.filter(CheckIfGreaterThanI);
this.unsubscribe(observersToUnsubscribe);
return;
}
};
};
return {
// Get the Singleton instance if one exists
// or create one if it doesn't
getInstance: function ()
{
if ( !instance )
{
instance = init();
}
return instance;
}
};
})();
function B (name,value,a) //observer
{
this.Name = name;
this.P = value;
this.A = a;
this.getName = function()
{
return this.Name;
};
this.getP = function()
{
return this.P;
};
this.update = function()
{
if(A.getInstance().getI()<this.P)
{
console.log("OK - " + this.Name);
}
};
};
for(j=0;j<10;j++)
{
var bObject = new B(j,Math.random(),A.getInstance());
A.getInstance().subscribe(bObject);
}
var ChangeIValue = function()
{
A.getInstance().setI(Math.random());
}
setTimeout(function run()
{
ChangeIValue();
setTimeout(run,1000);
}
, 1000);

Aliasing or otherwise merging two identical object prototypes with different names

I've got two object prototypes like this:
function Tag(name, description) {
this.name = name;
this.description = description || null;
}
function Category(name, description) {
this.name = name;
this.description = description || null;
}
Both of them are exactly the same, which seems awkward. Is it possible to merge them both into an object named 'Entity', and refer to them both by different names (the original 'Tag' and 'Category')?
This may be further complicated by the fact I need to refer to the current prototype name inside the prototype.
Tag.prototype.toJSON = function() {
return {
__type: 'Tag',
name: this.name,
description: this.description
};
};
How can I apply the same 'toJSON' extension to the 'Entity' object, but make sure it returns 'Tag' or 'Category' in the '__type' field, dependent on which object is being used?
I would do something like this:
Dummy = function () {};
Entity = function (name) {
this.name = name;
};
Entity.prototype.toString = function () {
return "My name is " + this.name + ".";
};
A = function () {
Entity.call(this, 'A');
};
Dummy.prototype = Entity.prototype;
Dummy.prototype.constructor = A;
A.prototype = new Dummy();
B = function () {
Entity.call(this, 'B');
};
Dummy.prototype = Entity.prototype;
Dummy.prototype.constructor = B;
B.prototype = new Dummy();
document.body.innerHTML = ""
+ (new A()) + "<br />"
+ (new B());
Here is a small function to make things cleaner (hopefully):
function Nothing () {};
function extend (Sup, proto) {
function Class () {
if (this.init) {
this.init.apply(this, arguments);
}
}
Nothing.prototype = Sup.prototype;
Nothing.prototype.constructor = Sup;
Class.prototype = new Nothing();
delete Nothing.prototype;
for (var k in proto) {
Class.prototype[k] = proto[k];
}
return Class;
}
Here is how to use it:
Entity = extend(Nothing, {
init: function (name) {
this.name = name;
},
toString: function () {
return "My name is " + this.name + ".";
}
});
A = extend(Entity, {
init: function () {
var sup = Entity.prototype;
sup.init.call(this, 'A');
}
});
B = extend(Entity, {
init: function () {
var sup = Entity.prototype;
sup.init.call(this, 'B');
}
});

Write getters as a prototype

I'm working on making performance updates on my javascript code.
In Firefox I got this warning:
mutating the [[Prototype]] of an object will cause your code to run very slowly; instead create the object with the correct initial [[Prototype]] value using Object.create
I wrote some scripts to prove this, and the results are great: without mutation a simple script runs 66% faster.
But I have trouble converting my code without mutation, I can't write the getters:
This is what I have now:
// Class
function FooBar(options) {
this.options = options;
}
// Prototype
FooBar.prototype = {
// Getters
get a() {
return this.options.a;
},
get b() {
return this.options.b;
},
get ab() {
return this.options.a + this.options.b;
},
// Methods
displayOptions: function() {
console.log(this.options);
}
};
// Code
var options = {
a: 'foo',
b: 'bar'
};
var fooBar = new FooBar(options);
console.log(fooBar.a);
console.log(fooBar.b);
console.log(fooBar.ab);
fooBar.displayOptions();
The getters as a prototype using the this keyword in their return are the problem.
If I use Object.defineProperty the this keyword is wrong, unless I do it inside the constructor, but it would recreate the property on each instance of the class and slow my code down even further.
This works (I just messed up the syntax in my previous attempt):
// Class
function FooBar (options) {
this.options = options;
}
//Prototype getters
Object.defineProperty(FooBar.prototype, 'a', {
get: function() {
return this.options.a;
}
});
Object.defineProperty(FooBar.prototype, 'b', {
get: function() {
return this.options.b;
}
});
Object.defineProperty(FooBar.prototype, 'ab', {
get: function() {
return this.options.a + this.options.b;
}
});
// Methods
FooBar.prototype.displayOptions = function() {
console.log(this.options);
};
// Code
var options = {
a:'foo',
b:'bar'
};
var fooBar = new FooBar (options);
console.log(fooBar.a);
console.log(fooBar.b);
console.log(fooBar.ab);
fooBar.displayOptions();
For those who are curious about the benefits of converting scripts like this to run faster: Run following code and look to your output in the console (Chrome - 66% faster, Firefox - no difference (curious, since I got the warning from Firefox)):
// WITHOUT PROTOTYPING
var Person1 = function() {
this.name = 'myName';
this.changeName = function(name) {
this.name = name;
};
this.changeName2 = function(name) {
this.name = name;
};
this.changeName3 = function(name) {
this.name = name;
};
this.changeName4 = function(name) {
this.name = name;
};
}
// WITH PROTOTYPING, WITH MUTATION
var Person2 = function() {
this.name = 'myName';
}
Person2.prototype = {
changeName: function(name) {
this.name = name;
},
changeName2: function(name) {
this.name = name;
},
changeName3: function(name) {
this.name = name;
},
changeName4: function(name) {
this.name = name;
}
};
// WITH PROTOTYPING, WITHOUT MUTATION
var Person3 = function() {
this.name = 'myName';
}
Person3.prototype.changeName = function(name) {
this.name = name;
};
Person3.prototype.changeName2 = function(name) {
this.name = name;
};
Person3.prototype.changeName3 = function(name) {
this.name = name;
};
Person3.prototype.changeName4 = function(name) {
this.name = name;
};
// DO THE TEST
var i=0, len=1000000;
// TEST1
window.performance.mark('mark_test_start');
for(i=0;i<len;i++) {
p = new Person1();
p.changeName('myName2');
}
window.performance.mark('mark_test_end');
window.performance.measure('no-prototyping', 'mark_test_start', 'mark_test_end');
// TEST2
window.performance.mark('mark_test2_start');
for(i=0;i<len;i++) {
p = new Person2();
p.changeName('myName2');
}
window.performance.mark('mark_test2_end');
window.performance.measure('prototyping-with-mutation', 'mark_test2_start', 'mark_test2_end');
// TEST3
window.performance.mark('mark_test3_start');
for(i=0;i<len;i++) {
p = new Person2();
p.changeName('myName2');
}
window.performance.mark('mark_test3_end');
window.performance.measure('prototyping-without-mutation', 'mark_test3_start', 'mark_test3_end');
// OUTPUT tests
var items = window.performance.getEntriesByType('measure');
for (var i = 0; i < items.length; ++i) {
var req = items[i];
console.log(req.name + ': ' + req.duration.toFixed(2));
}

Create a simpler way of nesting functions

I'm looking to lower my overhead on code like this
foo(bar(baz("hello"))) // function hell
ideally something like this
var fbb = bind(foo, bar, baz)
foo("hello")
Does this exist? Native or library?
I looked through underscore and bind.
Underscore has the compose function which will do what you want:
var composite = _.compose(foo, bar, baz);
composite('hello');
function foo(a1){
return 'foo' + a1;
}
function bar(a2){
return 'bar' + a2;
}
function baz(a3){
return 'baz' + a3;
}
alert(foo(bar(baz("hello"))));
var composite = _.compose(foo, bar, baz);
alert( composite('hello') );
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore-min.js"></script>
function getCaller(first) {
var rest = Array.prototype.slice.call(arguments, 1);
return function (value) {
return rest.reduce(function (previous, next) {
return next(previous);
}, first(value));
};
}
function foo(string) {
return string + ' world!';
}
function bar(string) {
return string + ' Hi';
}
function baz(string) {
return string + ' Mom!';
}
var caller = getCaller(foo, bar, baz);
console.log(caller('Hello'));
// Prints: Hello world! Hi Mom!
var bind = function() {
var fns = Array.prototype.slice.call(arguments).reverse();
return function(value) {
for (var key in fns) {
var fn = fns[key];
console.log(fn);
value = fn(value);
}
return value;
}
}
function plusTomato(value) {
return value + "tomato";
}
function plusPear(value) {
return value + "pear";
}
var plus = bind(plusTomato, plusPear);
var y = plus("pancake"); //pankaketomatopear
console.log(y);
var x = plusTomato(plusPear("pancake")); //pankaketomatopear
console.log(x);

Javascript functional inheritance with prototypes

In Douglas Crockford's JavaScript: The Good Parts he recommends that we use functional inheritance. Here's an example:
var mammal = function(spec, my) {
var that = {};
my = my || {};
// Protected
my.clearThroat = function() {
return "Ahem";
};
that.getName = function() {
return spec.name;
};
that.says = function() {
return my.clearThroat() + ' ' + spec.saying || '';
};
return that;
};
var cat = function(spec, my) {
var that = {};
my = my || {};
spec.saying = spec.saying || 'meow';
that = mammal(spec, my);
that.purr = function() {
return my.clearThroat() + " purr";
};
that.getName = function() {
return that.says() + ' ' + spec.name + ' ' + that.says();
};
return that;
};
var kitty = cat({name: "Fluffy"});
The main issue I have with this is that every time I make a mammal or cat the JavaScript interpreter has to re-compile all the functions in it. That is, you don't get to share the code between instances.
My question is: how do I make this code more efficient? For example, if I was making thousands of cat objects, what is the best way to modify this pattern to take advantage of the prototype object?
Well, you just can't do it that way if you plan on making lots of mammal or cat. Instead do it the old fashioned way (prototype) and inherit by property. You can still do the constructors the way you have above but instead of that and my you use the implicit this and some variable representing the base class (in this example, this.mammal).
cat.prototype.purr = function() { return this.mammal.clearThroat() + "purr"; }
I'd use another name than my for base access and store it in this in the cat constructor. In this example I used mammal but this might not be the best if you want to have static access to the global mammal object. Another option is to name the variable base.
Let me introduce you to Classical Inheritance that never uses prototype. This is a bad coding exercise but will teach you the real Classical Inheritance which always compared to prototypal inheritance:
Make a custructor:
function Person(name, age){
this.name = name;
this.age = age;
this.sayHello = function(){return "Hello! this is " + this.name;}
}
Make another cunstructor that inherits from it:
function Student(name, age, grade){
Person.apply(this, [name, age]);
this.grade = grade
}
Very simple! Student calls(applies) Person on itself with name and age arguments takes care of grade arguments by itself.
Now lets make an instance of Student.
var pete = new Student('Pete', 7, 1);
Out pete object will now contain name, age, grade and sayHello properties. It owns all those properties. They are not uplinked to Person through prototype. If we change Person to this:
function Person(name, age){
this.name = name;
this.age = age;
this.sayHello = function(){
return "Hello! this is " + this.name + ". I am " this.age + " years old";
}
}
pete will no recieve the update. If we call pete.sayHello, ti will return Hello! this is pete. It will not get the new update.
if you want privacy and you dont like protyping you may or may-not like this approach:
(note.: it uses jQuery.extend)
var namespace = namespace || {};
// virtual base class
namespace.base = function (sub, undefined) {
var base = { instance: this };
base.hierarchy = [];
base.fn = {
// check to see if base is of a certain class (must be delegated)
is: function (constr) {
return (this.hierarchy[this.hierarchy.length - 1] === constr);
},
// check to see if base extends a certain class (must be delegated)
inherits: function (constr) {
for (var i = 0; i < this.hierarchy.length; i++) {
if (this.hierarchy[i] == constr) return true;
}
return false;
},
// extend a base (must be delegated)
extend: function (sub) {
this.hierarchy.push(sub.instance.constructor);
return $.extend(true, this, sub);
},
// delegate a function to a certain context
delegate: function (context, fn) {
return function () { return fn.apply(context, arguments); }
},
// delegate a collection of functions to a certain context
delegates: function (context, obj) {
var delegates = {};
for (var fn in obj) {
delegates[fn] = base.fn.delegate(context, obj[fn]);
}
return delegates;
}
};
base.public = {
is: base.fn.is,
inherits: base.fn.inherits
};
// extend a sub-base
base.extend = base.fn.delegate(base, base.fn.extend);
return base.extend(sub);
};
namespace.MyClass = function (params) {
var base = { instance: this };
base.vars = {
myVar: "sometext"
}
base.fn = {
init: function () {
base.vars.myVar = params.myVar;
},
alertMyVar: function() {
alert(base.vars.myVar);
}
};
base.public = {
alertMyVar: base.fn.alertMyVar
};
base = namespace.base(base);
base.fn.init();
return base.fn.delegates(base,base.public);
};
newMyClass = new namespace.MyClass({myVar: 'some text to alert'});
newMyClass.alertMyVar();
the only downside is that because of the privacy scope you can only extend the virtual classes and not the instanceable classes.
here is an example of how i extend the namespace.base, to bind/unbind/fire custom events.
// virtual base class for controls
namespace.controls.base = function (sub) {
var base = { instance: this };
base.keys = {
unknown: 0,
backspace: 8,
tab: 9,
enter: 13,
esc: 27,
arrowUp: 38,
arrowDown: 40,
f5: 116
}
base.fn = {
// bind/unbind custom events. (has to be called via delegate)
listeners: {
// bind custom event
bind: function (type, fn) {
if (fn != undefined) {
if (this.listeners[type] == undefined) {
throw (this.type + ': event type \'' + type + '\' is not supported');
}
this.listeners[type].push(fn);
}
return this;
},
// unbind custom event
unbind: function (type) {
if (this.listeners[type] == undefined) {
throw (this.type + ': event type \'' + type + '\' is not supported');
}
this.listeners[type] = [];
return this;
},
// fire a custom event
fire: function (type, e) {
if (this.listeners[type] == undefined) {
throw (this.type + ': event type \'' + type + '\' does not exist');
}
for (var i = 0; i < this.listeners[type].length; i++) {
this.listeners[type][i](e);
}
if(e != undefined) e.stopPropagation();
}
}
};
base.public = {
bind: base.fn.listeners.bind,
unbind: base.fn.listeners.unbind
};
base = new namespace.base(base);
base.fire = base.fn.delegate(base, base.fn.listeners.fire);
return base.extend(sub);
};
To proper use Javascript-prototype based inheritance you could use fastClass https://github.com/dotnetwise/Javascript-FastClass
You have the simpler inheritWith flavor:
var Mammal = function (spec) {
this.spec = spec;
}.define({
clearThroat: function () { return "Ahem" },
getName: function () {
return this.spec.name;
},
says: function () {
return this.clearThroat() + ' ' + spec.saying || '';
}
});
var Cat = Mammal.inheritWith(function (base, baseCtor) {
return {
constructor: function(spec) {
spec = spec || {};
baseCtor.call(this, spec);
},
purr: function() {
return this.clearThroat() + " purr";
},
getName: function() {
return this.says() + ' ' + this.spec.name + this.says();
}
}
});
var kitty = new Cat({ name: "Fluffy" });
kitty.purr(); // Ahem purr
kitty.getName(); // Ahem Fluffy Ahem
And if you are very concerned about performance then you have the fastClass flavor:
var Mammal = function (spec) {
this.spec = spec;
}.define({
clearThroat: function () { return "Ahem" },
getName: function () {
return this.spec.name;
},
says: function () {
return this.clearThroat() + ' ' + spec.saying || '';
}
});
var Cat = Mammal.fastClass(function (base, baseCtor) {
return function() {
this.constructor = function(spec) {
spec = spec || {};
baseCtor.call(this, spec);
};
this.purr = function() {
return this.clearThroat() + " purr";
},
this.getName = function() {
return this.says() + ' ' + this.spec.name + this.says();
}
}
});
var kitty = new Cat({ name: "Fluffy" });
kitty.purr(); // Ahem purr
kitty.getName(); // Ahem Fluffy Ahem
Btw, your initial code doesn't make any sense but I have respected it literally.
fastClass utility:
Function.prototype.fastClass = function (creator) {
var baseClass = this, ctor = (creator || function () { this.constructor = function () { baseClass.apply(this, arguments); } })(this.prototype, this)
var derrivedProrotype = new ctor();
if (!derrivedProrotype.hasOwnProperty("constructor"))
derrivedProrotype.constructor = function () { baseClass.apply(this, arguments); }
derrivedProrotype.constructor.prototype = derrivedProrotype;
return derrivedProrotype.constructor;
};
inheritWith utility:
Function.prototype.inheritWith = function (creator, makeConstructorNotEnumerable) {
var baseCtor = this;
var creatorResult = creator.call(this, this.prototype, this) || {};
var Derrived = creatorResult.constructor ||
function defaultCtor() {
baseCtor.apply(this, arguments);
};
var derrivedPrototype;
function __() { };
__.prototype = this.prototype;
Derrived.prototype = derrivedPrototype = new __;
for (var p in creatorResult)
derrivedPrototype[p] = creatorResult[p];
if (makeConstructorNotEnumerable && canDefineNonEnumerableProperty) //this is not default as it carries over some performance overhead
Object.defineProperty(derrivedPrototype, 'constructor', {
enumerable: false,
value: Derrived
});
return Derrived;
};
define utility:
Function.prototype.define = function (prototype) {
var extendeePrototype = this.prototype;
if (prototype)
for (var p in prototype)
extendeePrototype[p] = prototype[p];
return this;
}
[* Disclaimer, I am the author of the open source package and the names of the methods themselves might be renamed in future` *]

Categories