Javascript and prototypal Inheritance - javascript

Is there a difference between these two statements in Javascript?
function p() {
this.do = function(){alert('cool')};
}
and this one?:
function p(){};
p.prototype.do = function(){alert('cool')};
One more thing, why can't you do:
function p(){};
p.do = function(){alert('cool')};
Thank you so much!

Given your first two examples, assuming you call p() as a constructor:
on the surface, they will behave identically
But the first example...
will create a new, identical function for each object created from new p()
[that function] will have access to the local variables and parameters inside the p() constructor
// p.prototype = {}
new p(); // { do:function(){alert('cool')}; } ------^
new p(); // { do:function(){alert('cool')}; } ------^
new p(); // { do:function(){alert('cool')}; } ------^
and the second example...
will share the function placed on the prototype between all the objects created from new p()
[that function] will not have access to private variables/parameters in the constructor
//p.prototype = {do:function(){alert('cool')};}
new p(); // {} ------^
new p(); // {} ------^
new p(); // {} ------^
The third example does not work because in JavaScript, a function is an object, so all you're doing it placing a new property on that object. It has no effect on the invocation of that function.

Functionally speaking, they are the same.
The first one defines a function for each object var o = new p() so it is not optimal from a memory viewpoint.
You can do what you're showing in your 3rd example, but you're not going to accomplish what you think:
function p(){};
p.do = function(){alert('cool')};
p.do(); // this will work
var o = new p(); // This won't have the 'do' function because that's not how it works in javascript.

Related

Add self executing init method to constructor function?

Let’s say I have a constructor function which I do not have access to. Into this constructor function I want to inject a self executing init method which gets executed whenever a new instance gets created from this constructor.
For example: let’s say there is a Cat constructor, but I unfortunatly do not have access to it:
function Cat() {
// ...code which I do not have access to
// ...maybe it comes from an external file or something?
}
And I can now of course do this to create new cats:
var coolCat = new Cat();
All is well and I have my new cat instance.
But now what I want is (if I actaully had access to the Cat constructor function body, which of course I do not!) something like this:
function Cat() {
this.roarOnInit = function() {
alert(’ROOOAAAR!’);
};
this.roarOnInit();
}
…so that when I do this:
var coolCat = new Cat();
…I actually get that cool ROAR-alert box!
I do understand how to add the method roarOnInit to the Cat constructor (Cat.prototype.roarOnInit = function …) but is there a way that I easily can add the call to the method (which gets executed whenever a Cat instance is created) to the constructor body?
This seems like such a trivial thing, and it’s probably super easy, but I just can’t seem to figure this out this afternoon! Thanks for bearing with me.
UPDATE
Thanks for the answers so far! I did forget one very important thing, and that is that I will not know in advance what the constructor function will be, or it's name etc. This is because I'm running this through a function which accepts any constructor as a parameter, and eventually returns the constructor (with it's original name/prototype) back.
Let's start with this definition of Cat:
function Cat(name){
this.name=name;
}
Cat.prototype.meow=function(){alert(this.name)}
Now, what we can do is to overwrite this with a new constructor that returns a regular Cat, but only after running our script:
var oldCat = Cat;
function Cat(name){
var self=new oldCat(name);
self.roarOnInit=function(){alert("ROOOOAAARRR")};
self.roarOnInit();
return self;
}
We can now do new Cat("Muffin"), and it will roar, and we'll still have access to properties on the original Cat prototype chain. I show this in an example snippet:
// just to be safe, define the original as oldCat()
function oldCat(name){
this.name=name;
}
oldCat.prototype.meow=function(){alert(this.name)}
//var oldCat = Cat;
function Cat(name){
var self=new oldCat(name);
self.roarOnInit=function(){alert("ROOOOAAARRR")};
self.roarOnInit();
return self;
}
var coolCat = new Cat("Muffin");
coolCat.meow();
Now, if you want to abstract this to accept any function, it's not too hard. We just have to do a bit of work with the constructor, to pass arguments. Javascript - Create instance with array of arguments
function injectToConstructor(C){
return function(){
var self = new (C.bind.apply(C,[C].concat([].slice.call(arguments))))();
console.log("object initiated:");
console.log(self);
return self;
};
}
Then we can do something like:
Cat = injectToConstructor(Cat);
var coolCat = new Cat("Muffin"); // logs 2 items
coolCat.meow();
This is because I'm running this through a function which accepts any constructor as a parameter, and eventually returns the constructor (with it's original name/prototype) back.
You cannot really. It's impossible to alter a function's behaviour, no way to "inject" code into it. The only way is to wrap the function, i.e. decorate it, and return a new one.
In your example, it would look like so:
function makeRoarer(constr) {
function Roar() { // new .name and .length, but that shouldn't matter
constr.apply(this, arguments);
this.roarOnInit();
}
Roar.prototype = constr.prototype;
Roar.prototype.constructor = Roar;
Roar.prototype.roarOnInit = function() {
alert(’ROOOAAAR!’);
};
return Roar;
}
class Cat { … } // whatever
var a = new Cat(); // nothing
Cat = makeRoarer(Cat);
var b = new Cat(); // ROOOAAAR!

javascript create new object by avoiding new keywords

JavaScript can create a object in many ways.
I try the following code to avoid new keyword to create a new Object of Class A.
My question is that A.prototype.init() here is whether equals new A()? is this good for practice, and why?
function A(){
}
A.prototype.init=function(){
return this;
}
var a = A.prototype.init();
console.log(a);
var a1=new A();
console.log(a1);
jsfiddle
All you're doing is returning the A.prototype object. You're not really initializing anything, and you're not using the result.
console.log(A.prototype === A.prototype.init()); // true
So unless you have a particular use in mind, I'd say, no it's not a good practice.
Not sure exactly why you want to avoid new, but in any case, you can change your constructor so that it can be called with or without new and still behave like a constructor.
function A() {
var ths = Object.create(A.prototype);
ths.foo = "bar";
return ths;
}
Now it won't matter if you use new. You're going to get a new object that inherits from A.prototype no matter what.
You can still use an .init() method, but you might as well just put the logic in the constructor.
Furthermore, you can easily create a factory that takes care of that little bit of boilerplate code.
function Ctor(fn) {
return function() {
var ths = Object.create(fn.prototype);
fn.apply(ths, arguments);
return ths;
};
}
So now you'd create your constructor like this:
var A = Ctor(function() {
this.foo = "bar";
});
You can avoid new by encapsulating your code with the module pattern and returning a function that calls the constructor, in other words:
var A = (function ClassA() {
// Constructor
function A(prop) {
this.prop = prop; // instance property
this._init();
}
// Public methods
A.prototype = {
_init: function() {
}
};
// Mini factory to create new instances
return function(prop) {
return new A(prop); // well, only one `new`
};
}());
Now you can create new instances without new:
var a = A('foo'); //=> A { prop: "foo", init: function }
Usually you catch direct function calls with instanceof:
function MyConstructor (a, b, c) {
if (!(this instanceof MyConstructor)) {
return new MyConstructor(a, b, c);
}
// ...
}
but there is no good reason to avoid using new. Object.create and other alternatives can have a significant performance impact.

Copy and modify similar object for instantiation javascript

I have an object that looks like
var customObject = function() {
this.property = "value";
};
customObject.prototype = new otherObject();
customObject.prototype.property2 = function() {};
etc. - it's much bigger than this.
I can successfully instantiate the object by writing new customObject().
Now I would like to create a rather similar object, although a little different. This involves modifying certain properties and perhaps even adding or removing some. As in the above example, I would like it to be invokable by writing new customObject2().
I thought I could simply do:
var customObject2 = new customObject();
customObject2.prototype = customObject.prototype;
customObject2.property = "modified value";
etc.
However, when I try to instantiate it by doing new customObject2() I receive an error, stating that the customObject2 is not a function.
I hope I could illustrate well enough as to what pattern I desire to create. What approach should I take to create such a pattern?
If customObject is not a host object (i.e. won't give you an illegal invocation error if you try to call it differently to expected) you can apply the constructor to a different this Object;
var customObject2 = function () {
customObject.call(this); // construct as if `customObject`
// now do more stuff
this.anotherProperty = 'foo';
};
customObject2.prototype = Object.create(customObject.prototype);
// inherit prototype but keep original safe
new customObject2();
Backwards compatible Object.create
function objectWithProto(proto) {
var f;
if (Object.create) return Object.create(proto);
f = function () {};
f.prototype = proto;
return new f();
}
I think this should answer your question. Basically, the new keyword is returning an object and not a function.
Why are you not using the same formula you used the first time? For example:
var customObject2 = function(){};
customObject2.prototype = new customObject();
customObject2.property = "modified value";
new customObject2(); // works!
All properties of customObject will be inherited by the instances of customObject2 through the prototype chain.

Why won't this object's prototype's init function run

I use the following function for creating new objects.
function newObj(o) {
var params = Array.prototype.slice.call(arguments,1);
function F() {}
F.prototype = o;
var obj = new F();
if(params.length) {
obj.init.apply(obj,params);
}
return obj;
}
And it works well most of the time. However one of my base "classes" is now defined as inheriting from another base class
SPZ.EditablePuzzle = function () {
// function and variable definitions
return {
///some methods and properties
}
}();
SPZ.EditablePuzzle.prototype = SPZ.Puzzle;
Now when I use newObj() to create a new SPZ.EditablePuzzle the init function is not defined even though it is defined in SPZ.Puzzle and I make sure EditablePuzzle runs after Puzzle
Why won't my newObj function find the init function? Shouldn't it automatically look in the prototype as soon as it fails to find it in the object itself?
I suspect the inheritance is not well set. try doing
SPZ.EditablePuzzle.prototype = new SPZ.Puzzle;
Might solve this problem, though I am not sure.
Concerning the problem:
function Foo() {
}
Foo.prototype.init = function() {
console.log('bla');
};
function FooBar() {
}
FooBar.prototype = Foo; // looks fishy...
var kitten = new FooBar();
console.log(kitten.init); // yields undefined, uh what?
The problem is, that in this case Foo itself gets assigned to the prototype property, when in fact you wanted to do:
FooBar.prototype = Foo.prototype
See the difference? Foo has no init property as it is defined on the prototype object.

javascript singleton question

I just read a few threads on the discussion of singleton design in javascript. I'm 100% new to the Design Pattern stuff but as I see since a Singleton by definition won't have the need to be instantiated, conceptually if it's not to be instantiated, in my opinion it doesn't have to be treated like conventional objects which are created from a blueprint(classes). So my wonder is why not just think of a singleton just as something statically available that is wrapped in some sort of scope and that should be all.
From the threads I saw, most of them make a singleton though traditional javascript
new function(){}
followed by making a pseudo constructor.
Well I just think an object literal is enough enough:
var singleton = {
dothis: function(){},
dothat: function(){}
}
right? Or anybody got better insights?
[update] : Again my point is why don't people just use a simpler way to make singletons in javascript as I showed in the second snippet, if there's an absolute reason please tell me. I'm usually afraid of this kind of situation that I simplify things to much :D
I agree with you, the simplest way is to use a object literal, but if you want private members, you could implement taking advantage of closures:
var myInstance = (function() {
var privateVar;
function privateMethod () {
// ...
}
return { // public interface
publicMethod1: function () {
// private members can be accessed here
},
publicMethod2: function () {
// ...
}
};
})();
About the new function(){} construct, it will simply use an anonymous function as a constructor function, the context inside that function will be a new object that will be returned.
Edit: In response to the #J5's comment, that is simple to do, actually I think that this can be a nice example for using a Lazy Function Definition pattern:
function singleton() {
var instance = (function() {
var privateVar;
function privateMethod () {
// ...
}
return { // public interface
publicMethod1: function () {
// private members can be accessed here
},
publicMethod2: function () {
// ...
}
};
})();
singleton = function () { // re-define the function for subsequent calls
return instance;
};
return singleton(); // call the new function
}
When the function is called the first time, I make the object instance, and reassign singleton to a new function which has that object instance in it's closure.
Before the end of the first time call I execute the re-defined singleton function that will return the created instance.
Following calls to the singleton function will simply return the instance that is stored in it's closure, because the new function is the one that will be executed.
You can prove that by comparing the object returned:
singleton() == singleton(); // true
The == operator for objects will return true only if the object reference of both operands is the same, it will return false even if the objects are identical but they are two different instances:
({}) == ({}); // false
new Object() == new Object(); // false
I have used the second version (var singleton = {};) for everything from Firefox extensions to websites, and it works really well. One good idea is to not define things inside the curly brackets, but outside it using the name of the object, like so:
var singleton = {};
singleton.dothis = function(){
};
singleton.someVariable = 5;
The ES5 spec lets us use Object.create():
var SingletonClass = (function() {
var instance;
function SingletonClass() {
if (instance == null) {
instance = Object.create(SingletonClass.prototype);
}
return instance;
}
return {
getInstance: function() {
return new SingletonClass();
}
};
})();
var x = SingletonClass.getInstance();
var y = SingletonClass.getInstance();
var z = new x.constructor();
This is nice, since we don't have to worry about our constructor leaking, we still always end up with the same instance.
This structure also has the advantage that our Singleton doesn't construct itself until it is required. Additionally, using the closure as we do here prevents external code from using our "instance" variable, accidentally or otherwise. We can build more private variables in the same place and we can define anything we care to export publically on our class prototype.
The singleton pattern is implemented by creating a class with a method that creates a new instance of the class if one does not exist. If an instance already exists, it simply returns a reference to that object. 1
(function (global) {
var singleton;
function Singleton () {
// singleton does have a constructor that should only be used once
this.foo = "bar";
delete Singleton; // disappear the constructor if you want
}
global.singleton = function () {
return singleton || (singleton = new Singleton());
};
})(window);
var s = singleton();
console.log(s.foo);
var y = singleton();
y.foo = "foo";
console.log(s.foo);
You don't just declare the singleton as an object because that instantiates it, it doesn't declare it. It also doesn't provide a mechanism for code that doesn't know about a previous reference to the singleton to retrieve it. The singleton is not the object/class that is returned by the singleton, it's a structure. This is similar to how closured variables are not closures, the function scope providing the closure is the closure.
I am just posting this answer for people who are looking for a reliable source.
according to patterns.dev by Lydia Hallie, Addy Osmani
Singletons are actually considered an anti-pattern, and can (or.. should) be avoided in JavaScript.
In many programming languages, such as Java or C++, it's not possible to directly create objects the way we can in JavaScript. In those object-oriented programming languages, we need to create a class, which creates an object. That created object has the value of the instance of the class, just like the value of instance in the JavaScript example.
Since we can directly create objects in JavaScript, we can simply use
a regular object to achieve the exact same result.
I've wondered about this too, but just defining an object with functions in it seems reasonable to me. No sense creating a constructor that nobody's ever supposed to call, to create an object with no prototype, when you can just define the object directly.
On the other hand, if you want your singleton to be an instance of some existing "class" -- that is, you want it to have some other object as its prototype -- then you do need to use a constructor function, so that you can set its prototype property before calling it.
The latter code box shows what I've seen JS devs call their version of OO design in Javascript.
Singetons are meant to be singular objects that can't be constructed (except, I suppose, in the initial definition. You have one, global instance of a singleton.
The point of using the "pseudo constructor" is that it creates a new variable scope. You can declare local variables inside the function that are available inside any nested functions but not from the global scope.
There are actually two ways of doing it. You can call the function with new like in your example, or just call the function directly. There are slight differences in how you would write the code, but they are essentially equivalent.
Your second example could be written like this:
var singleton = new function () {
var privateVariable = 42; // This can be accessed by dothis and dothat
this.dothis = function () {
return privateVariable;
};
this.dothat = function () {};
}; // Parentheses are allowed, but not necessary unless you are passing parameters
or
var singleton = (function () {
var privateVariable = 42; // This can be accessed by dothis and dothat
return {
dothis: function () {
return privateVariable;
},
dothat: function () {}
};
})(); // Parentheses are required here since we are calling the function
You could also pass arguments to either function (you would need to add parentheses to the first example).
Crockford (seems to) agree that the object literal is all you need for a singleton in JavaScript:
http://webcache.googleusercontent.com/search?q=cache:-j5RwC92YU8J:www.crockford.com/codecamp/The%2520Good%2520Parts%2520ppt/5%2520functional.ppt+singleton+site:www.crockford.com&cd=1&hl=en&ct=clnk
How about this:
function Singleton() {
// ---------------
// Singleton part.
// ---------------
var _className = null;
var _globalScope = null;
if ( !(this instanceof arguments.callee) ) {
throw new Error("Constructor called as a function.");
}
if ( !(_className = arguments.callee.name) ) {
throw new Error("Unable to determine class name.")
}
_globalScope = (function(){return this;}).call(null);
if ( !_globalScope.singletons ) {
_globalScope.singletons = [];
}
if ( _globalScope.singletons[_className] ) {
return _globalScope.singletons[_className];
} else {
_globalScope.singletons[_className] = this;
}
// ------------
// Normal part.
// ------------
var _x = null;
this.setx = function(val) {
_x = val;
}; // setx()
this.getx = function() {
return _x;
}; // getx()
function _init() {
_x = 0; // Whatever initialisation here.
} // _init()
_init();
} // Singleton()
var p = new Singleton;
var q = new Singleton;
p.setx(15);
q.getx(); // returns 15
I stole this from CMS / CMS' answer, and changed it so it can be invoked as:
MySingleton.getInstance().publicMethod1();
With the slight alternation:
var MySingleton = { // These two lines
getInstance: function() { // These two lines
var instance = (function() {
var privateVar;
function privateMethod () {
// ...
console.log( "b" );
}
return { // public interface
publicMethod1: function () {
// private members can be accessed here
console.log( "a" );
},
publicMethod2: function () {
// ...
privateMethod();
}
};
})();
singleton = function () { // re-define the function for subsequent calls
return instance;
};
return singleton(); // call the new function
}
}

Categories

Resources