Do we really have to change to Object.create? - javascript

I have a question for you
As I know, new operator works this way
function fakeNew(Ctor) {
var instance = Object.create(Ctor.prototype);
instance.constructor();
// I skip the conditional for simplicity
return instance;
}
It all begin when I did a Object.create polifill so I could create objects without using new.
Object.create = function(proto) {
function F() { }
F.prototype = proto;
return new F();
}
I started creating a lot of objcts and prototiping them, but as many times then need to initializa its properties I did a .init() method to them
var base = {
init: function() {
EmitterMixin.call(this);
return this;
}
};
var obj = Object.create(base).init();
But of course, I had to rembember to return this always from .init() and many times I forget it or worst, I forgot to call .init(). So trying to simplify object initialization I wanted to create a global helper to do it: invoke Object.create, invoke the initializer function and return this.
function create(proto) {
var child = Object.create(proto);
child.init();
return child;
}
Then was when I wanted to hit my head against the wall when I realized what I was doing was virtually what new operator does but a lot slower. And in case the polifill applies I would even use new under the hood.
So I ask myself, what benefits throwing new? It's notably quicker on main browsers and because of javascript nature we usually need to call a initualizer function, something than new does from it's begining.
And worst, I've noticed than I used two different types of objects, "abstract" and "instances", the bigger difference is than for instances I had to invoke .init() while with abstracts it was not necesasary because they will only be used to be prototypes of other objects. And I've already seen this pattern while using new:
function Foo() { }
Foo.prototype.method = function() { ... };
function Bar() { }
// "abstract" doesnt invoke initializer
Bar.prototype = Object.create(Foo.prototype);
Bar.prototype.other = function() { ... };
// "instance", the constructor is called as initializer
var obj = new Bar();
Is there really a benefit if we stop seeing new? are we sure it's not a higher-level tool than simplifies something we'll have to do anyway?
What pros/cons do you see about new and Object.create?

I have tried both approaches and I don't personally see any problem with the traditional approach using new. The main argument for Object.create is that it makes the prototypal inheritance more clear - you don't have to understand the intricacy of the prototype property on function constructors and how that relates to the actual prototype of the object. But it does require that initialization be a separate step.
My preferred approach is to combine the two approaches, e.g.:
function Animal(name) {
this.name = name || null;
}
Animal.prototype.eat = function() {
console.log('yum');
}
function Cat(name) {
Animal.call(this, name);
}
Cat.prototype = Object.create(Animal.prototype);
Cat.prototype.constructor = Cat;
Cat.prototype.meow = function() {
console.log('meow');
}
var garfield = new Cat('garfield');
garfield.eat();
garfield.meow();
Object.create is better for inheritance here than Cat.prototype = new Animal() for two reasons:
If you wanted to require the name parameter (throwing an exception if it wasn't passed), you could do so and the inheritance (Cat.prototype = Object.create(Animal.prototype)) would still work.
If you forgot to call the Cat constructor from the Animal constructor, all of the properties that would have been created by the Animal constructor will be undefined instead, allowing you to quickly realize the mistake.
Although this approach (using constructor functions and new) is less "purely" prototypal, it's still prototypal inheritance and as long as you understand how to use it correctly it works just fine, and requires a little less typing than the Object.create approach.
I wrote some other notes about this in the documentation for my Javascript OO library, simpleoo. (Note: I may be changing the API soon for that library; I'm linking to it mainly because the documentation discusses some of these concepts in more detail.)

Related

JavaScript inheritance: using __proto__ within constructor function, instead of construction function's prototype property

I was discussing Javascript OO strategies/patterns with a colleague, and from most tutorials I've read, the common way of establishing a prototype/inheritance relationship between two constructor functions (with arguments) is to assign a prototype to the child function.
e.g.:
var MyParentClass = function(arg1) { ... };
var MyChildClass = function(arg1, arg2) {
MyParentClass.apply(this, arguments);
...
};
MyChildClass.prototype = new MyParentClass;
One of the problems here is that the argument might be in a different order, or change names, etc., and the above example does require two (2) separate statements to establish the relationship (the apply() statement, and the .prototype statemetn).
My colleague suggested this approach instead:
var MyParentClass = function(arg1) { ... };
var MyChildClass = function(arg1, arg2) {
this.__proto__ = new MyParentClass(arg2);
...
};
This approach is shorter and gives more flexibility towards which arguments are passed to the parent constructor.
Unless I'm missing something, seems like this should be the de-facto pattern for establishing inheritance between JavaScript classes, so I'm curious as to why I've never come across that pattern in all JavaScript OO tutorials so far. Can anyone let me know if the above strategy has any downside?
You can address the Problem with passing parameters to the parent-constructor- function as follows:
Instead of
MyChildClass.prototype = new MyParentClass;
you can write
MyChildClass.prototype = Object.create(MyParentClass.protoype)
in that way you can assign the prototype without a new instantiation of MyParentClass
If you want to pass parameters from the constructorFunction from MyChildClass to MyParentClass you can do that like that:
function MyChildClass(arg1) {
MyParentClass.call(this, arg1);
}

Singleton and Prototyping in Javascript

I was just looking into ways of defining singletons in JavaScript, and after looking into a few samples I thought about the following way which I haven't found anywhere:
function MyClass() {
if (MyClass._sharedInstance === undefined) {
// actual constructor code
MyClass._sharedInstance = this;
}
return MyClass._sharedInstance;
}
MyClass._sharedInstance = undefined;
Seems to work fine... but the fact that I couldn't find this anywhere makes me suspicious. Is there any reason not to do a singleton that way, especially considering the many little pitfalls of JavaScript. I know that by simply doing a var MyClass = { /* MyClass Stuff */ } I can achieve a singleton with less code, but for the sake of consistency I would like to define all my classes using prototypes.
The proposed solution does not seem to "solve" anything1; as such,
I recommend a standard variation of a "simple module pattern" using an idiomatic IIFE:
MySingleton = (function () {
// This function is only executed once
// and whatever is returned is the singleton.
return {
// Expose members here
};
})();
Depending on specific need a new'ed object could also be returned, making this pattern flexible without the need to introduce a separate "singleton" field and guard, e.g.
MySingleton = (function () {
// Contrived, but valid - any object returned
// functions as the singleton.
function MyClass {}
return new MyClass();
})();
1If anything, it may lead to some "WTF?" moments when new MyClass() returns a shared/singleton object which is not "normal" behavior.

Prototypical Inheritance calls constructor twice

I'm working on a JavaScript project that uses Prototypical Inheritance. The way that I decided to use it is the following:
var MySuperClass = function (param) {
this.prop = param;
};
MySuperClass.prototype.myFunc = function () {
console.log(this.prop);
};
var MySubClass = function (param) {
MySuperClass.call(this, param);
};
MySubClass.prototype = new MySuperClass();
MySubClass.prototype.constructor = MySubClass;
var obj = new MySubClass('value');
obj.myFunc();
With the emphasis on the inheritance.
The issue with this is that if I put a console.log in the constructor of each class (the super and the sub), the super class is called twice, once when it is passed into the subclass with MySubClass.prototype = new MySuperClass(); without any parameters and once with parameters when it is 'constructor stolen' in the constructor of the sub class.
This can cause errors if I then try to save those parameters (meaning that I have to add logic to deal with empty params).
Now if I do this:
var MySubClass = function (param) {
MySuperClass.call(this, param);
};
MySubClass.prototype = MySuperClass;
MySubClass.prototype.constructor = MySubClass;
Everything seems to work correctly but I've never seen anyone do this before (in my Googl'ing).
Can anyone explain to me if and how the 2nd one is incorrect (it seems to be similar to the Crockford inheritance function) and how to fix the 1st one to not fire twice if it is please?
Doing this is not a correct solution:
MySubClass.prototype = MySuperClass;
You're setting the function itself as the prototype instead of the prototype object, so you're not inheriting what you'd expect.
But you are right. Doing this does invoke the constructor, which can cause problems.
MySubClass.prototype = new MySuperClass();
The solution is to use Object.create to set up the inheritance. It gives you a new object that inherits from the object provided, but doesn't invoke any constructor.
MySubClass.prototype = Object.create(MySuperClass.prototype);
Now you have an object assigned to MySubClass.prototype that inherits from MySuperClass.prototype, but you never had to actually invoke the constructor.
Non ES5 compliant implementations won't support Object.create, but you can make a (partial) shim for it.
if (!Object.create) {
Object.create = function(proto) {
function F(){}
F.prototype = proto;
return new F();
};
}
Again, this is not a full shim, but it emulates just enough to be able to make inherited objects without having to invoke the constructor that references the prototype object.

In Javascript, why does the constructor property point to the base-most constructor in the prototype chain?

I'm curious about this design of Javascript, and perhaps any reasons for this architecture or design patterns that can be employed to take advantage of this.
The constructor property of an object is always a reference to the function that created that object, correct?
However, take this code:
function base()
{
this.SayHi = function ()
{
window.alert('Hi');
};
}
function subclass()
{
this.SayBye = function ()
{
window.alert('Bye');
};
}
subclass.prototype = new base();
var s = new subclass();
s.SayHi();
s.SayBye();
window.alert(s.constructor);
The last line will echo the constructor for base, even though we know subclass was called to create the object (otherwise SayBye would not work).
One potential work-around would be to simply do:
subclass.prototype.constructor = subclass;
Perhaps a more concise way of asking my question is why is s.constructor equal to subclass.prototype.constructor and not subclass.constructor, since s is an instanceof subclass. Thanks!
All objects inherit a constructor property from their prototype.
Source.
That's just how it works. You often do see people explicitly setting the constructor property to something that seems more intuitive to them.

Baffling JavaScript Inheritance Behavior

<disclaimer>
What follows is the fruits of a thought experiment. What I'm doing
isn't the issue; the symptoms are. Thank you.
</disclaimer>
I've finally wrapped my head around constructors, prototypes, and prototypal inheritance in JavaScript. But the SomethingSpectactular method in the sample below bugs me:
function FinalClass() {
return {
FinalFunction : function() { return "FinalFunction"; },
TypeName : "FinalClass",
SomethingSpectacular : function() {
return FinalClass.prototype.SubFunction.call(this);
}
}
}
FinalClass.prototype = new SubClass();
FinalClass.constructor = FinalClass;
var f = new FinalClass();
The reasons this bugs me are:
JavaScript apparently doesn't scan the prototype chain the same way for methods as it does for properties. That is, f.SubFunction() generates an error.
To get to a method on a prototype, you have to go through at least 3 dot operations every time you want to do it. FinalClass DOT prototype DOT Subfunctino DOT call. You get the point.
Base class (prototype) methods aren't showing up in Intellisense the way I'd expect them to. This is highly annoying.
So the thought experiement was to determine what would happen if I wrote a version of inherits that inserted stub functions onto the subclass that delegated back to the prototype for you. For example, it would automatically create the following function and add it to FinalClass:
function SubFunction() { SubClass.prototype.SubFunction.call(this); }
Now, I've got just about everything mapped out and working. The inherits method, which is an extension to both Object.prototype and Function.prototype, takes a Function as its sole argument. This is the base class. The subclass is determined by analyzing Object.prototype.inherits.caller.
From there, I set the prototype and constructor on the subclass, and then start analyzing the methods on the subclass's new prototype. I build an array containing the methods on both the prototype and the base class's public interface. The end result is a nice array that contains the methods that are exposed through either the prototype or by the base class constructor's return statement.
Once I have that, I start looking for each method on the subclass. If it's not there, I add it to the subclass with the same name and signature. The body of the method, however, simply forwards the call to the base class.
Now, I can step through all this code and it works marvelously, up until I instantiate instances of the subclasses. That's when things get wonky. Here's what I've observed using Visual Studio 2008 (SP1) and Internet Explorer 8:
Prior to instantiation, BaseClass exposes no public methods. This is to be expected. The methods exposed via a class constructor's return statement won't appear until it's instantiated. I'm good with that.
Prior to instantiation, SubClass exposes the methods from BaseClass. This is exactly what I expected.
Once I declare an instance of BaseClass, it has all the members I would expect. It has its typeName and BaseFunction methods.
Once I declare an instance of SubClass, it has only those methods returned by its constructor's return statement. No members from the base class are present. All the work that was done in the inherits method to map base class methods to the subclass appears to have been lost.
The big mystery for me here is the disappearance of the methods that I added to SubClass during the execution of inherits. During its execution, I can clearly see that SubClass is being modified, and that BaseClass's functions are being propagated. But the moment I create an instace of SubClass, that information is no longer present.
I am assuming this has something to do with the constructor, or order of events, or something else that I am simply not seeing.
A Final Note: This project arose as an effort to understand the complexities of JavaScript and how its prototypal inheritance system works. I know there are existing libraries out there. I know I'm reinventing the wheel. I'm reinventing it on purpose. Sometimes, the best way to understand a thing is to build it yourself. This has already been a tremendous learning experience, but I'm just stumped at this one particular point.
THE CODE
sti.objects.inherits = function inherits(baseClass) {
var subClass = sti.objects.inherits.caller;
var baseClassName = sti.objects.getTypeName(baseClass);
var methods = sti.objects.getMethods(baseClass);
if(!sti.objects.isDefined(baseClass.typeName))
baseClass.typeName = baseClassName;
var subClass = sti.objects.inherits.caller;
var subClassName = sti.objects.getTypeName(subClass);
var temp = function() {};
temp.prototype = new baseClass();
subClass.prototype = temp.prototype;
subClass.constructor = subClass;
subClass.typeName = subClassName;
subClass.baseClass = baseClass.prototype; // Shortcut to the prototype's methods
subClass.base = baseClass; // Cache the constructor
for(var index = 0; index < methods.items.length; index++) {
var resource = methods.items[index].getFunction();
var methodName = methods.items[index].getName();
if(methodName != "" && ! sti.objects.isDefined(subClass[methodName])) {
var method = sti.objects.createOverride(baseClassName, resource);
subClass[methodName] = method;
if(typeof subClass.prototype[methodName] == "undefined") {
subClass.prototype[methodName] = method;
}
}
}
}
Object.prototype.inherits = sti.objects.inherits;
Function.prototype.inherits = sti.objects.inherits;
function BaseClass() {
return {
A : function A() {return "A";}
};
}
function SubClass() {
inherits(BaseClass);
return {
B : function B() { return "B"; }
}
}
var b = new BaseClass();
var s = new SubClass();
Your constructors are not working as constructors. When you use the new keyword Javascript creates the new object and expects your constructor to populate it with members etc. Your constructors are returning another new object, not related to the object which is associated with the constructor usage, thus the prototype is not working.
Change your constructor to something like
function FinalClass() {
this.FinalFunction = function() { return "FinalFunction"; };
this.TypeName = "FinalClass";
this.SomethingSpectacular = function() {
return FinalClass.prototype.SubFunction.call(this);
};
}
and you should see the expected inheritance behaviour. This is because the FinalClass method in this case alters the contextual object created via the 'new' mechanism. Your original method is creating another object which is not of type FinalClass.

Categories

Resources