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!
Related
How does the new work differently in the 2 examples below? I see that the 2nd example is replacing the annoymous funciton with a variable, but in the second one, the function/class "Person" is actually being called. Does it make any difference if it's being called or not? I tried it without the calling and it still worked. So that led me to believe that new is actually calling the function and setting up this to be assigned to the instance variable.
var person = new function() {
this.setName = function(name) {
this.name = name;
}
this.sayHi = function() {
return "Hi, my name is " + this.name;
}
}
person.setName("Rafael");
console.log(person.sayHi()); // Hi, my name is Rafael
var Person = function() {
this.setName = function(name) {
this.name = name;
}
this.sayHi = function() {
return "Hi, my name is " + this.name;
}
}
var personTwo = new Person()
personTwo.setName("Rafael");
console.log(personTwo.sayHi()); // Hi, my name is Rafael
There would be almost no difference between these two examples, if it was a simple function like this:
(function() { console.log("IIFE"); })();
// or
var f = function() { console.log("Function"); };
f();
You just store your function in a variable, and then call it.
However, it makes a little difference, since it is related to JS OOP mechanisms. In the first case you get Object instance, and in the second you get Person instance. This makes difference in OOP sense.
var person = new function() { };
console.log("Is instance of: " + person.constructor.name);
console.log("There is no way to check instanceof in this case");
var Person = function() { };
var person = new Person();
console.log("Is instance of: " + person.constructor.name);
console.log(person instanceof Person);
In general, new and classes are supposed to be used as in the second case in order to enable the full functionality of JS OOP. There is absolutely no sense or/and advantage in using anonymous class constructor.
Whether or not it is assigned into a variable: does not matter. It is completely parallel to this example:
var x = 1;
console.log(x);
and
console.log(1);
Whether it needs to be called or not: A function with the new operator is always being called, but with new, parentheses are optional when no parameters are passed: new Person() is equivalent to new Person, but new Person("Joe") cannot be done differently.
In the second example, you are passing to the new operator the exact same function. You simply are using a reference (logically stored in a variable) instead of writing literal function just in place.
So, your second example is the same as:
var personTwo = new (function() {
[...]
})()
[...]
Which, in fact, is much the same as the first one:
var person = new (function() {
[...]
})
[...]
NOTE that the parentheses surrounding the function are absolutely optional in this case. You could be placed there seven if you like: (((((((function(){[...]}))))))).
The point here is that when you say «in the second one, the function/class "Person" is actually being called» you are WRONG there: That function, which acts as a constructor isn't being called by you. You are simply passing it as a parameter (the constructor function) of the new operator which is, in fact, who is actually calling the constructor with the rest of parameters you provided, if any.
See new syntax documentation:
new constructor[([arguments])]
The constructor is the function you pass to the new operator and the parameters are specified between parentheses. But they are fully optional (including the parentheses itself).
This is why new constructor; without parentheses works.
To be clear: What you thought happens (but not) would be written as:
var person = new ((function(){...})()) ();
...or, more verbosely:
var person = new (
(function(){ // Constructor builder.
[...]
return function(){...}; // Actual constructor.
})() // Constructor builder call
//v-- Parentheses to force builder to be called.
) (); // <-- Parameters (if any) passed to the constructor.
I'm working on building a collection of prototype helper methods inside a wrapper. However for ease of use, I'd like to be able to call the object as both a new instance and single global instance under the same call.
For example, with jQuery, you can call both "$" and "$()" which can be used differently http://learn.jquery.com/using-jquery-core/dollar-object-vs-function/:
So given the bellow as simple example, how could I do something similar?
(function () {
var myWrapper = function (foo) {
return new helper(foo);
};
var helper = function (foo) {
this[0] = foo;
return this;
}
helper.prototype = {
putVar: function(foo) {
this[0] = foo;
}
}
if(!window.$) {
window.$ = myWrapper;
}
})();
// create an new instace;
var instance = $("bar");
console.log(instance);
// call a prototype method
instance.putVar("foo");
console.log(instance);
// call a prototype method using the same call without new instance
// this doesnt work :(
$.putVar("foo");
// however this will work
window.myLib = $("foo");
myLib.putVar("bar");
http://jsfiddle.net/2ywsunb4/
If you want to call $.putVar, you should define putVar like this:
myWrapper.putVar = function (foo) {
console.log('Work');
}
In your code, the instance and myLib are the same thing, they are both instances created by you.
If you want to call both $.putVar and $(...).putVar, you should add the code I show you above. That means you have to define two putVar functions, one is used like a 'instance' method, while the other one is used like a 'static' method.
If you search through jQuery source code, you will see two each functions defined. That's why you can all both $.each(...) and $(...).each for different usages.
I was looking at Static variables in JavaScript and I noticed something I'd seen before, that the function is defined and after the function definition the function prototype is updated:
function MyClass () { // constructor function
//function definition here
}
//now add a (static?) method *outside* the function definition
MyClass.prototype.publicMethod = function () {
alert(this.publicVariable);
};
//add a static property *outside* the function definition
MyClass.staticProperty = "baz";
Here's my question - why not define them inside the function defintion, like this:
function MyFunc(){
MyFunc.staticVar = 1;
//static method showing static var
MyFunc.showVarStatic = function(){
alert(MyFunc.staticVar);
}
//instance method referring to static var
this.showVarInstance = function(){
alert(MyFunc.staticVar);
}
//instance method - doesn't change static var
this.inc1 = function(){
this.staticVar += 1;//no such property
}
//static method, changes var
this.inc2 = function(){
MyFunc.staticVar += 1;//increments static property
}
}
This seems to behave as expected in IE8, FF, and Chrome. Is this just a personal preference / style thing? I like it, because my whole function is contained in those curly brackets.
[EDIT: after doing more reading and experimenting, I have better understand of how javascript functions are constructors, and how they differ from, for example, C# classes - here's some code I used to demonstrate this]
//this is deceiving, notSoStaticVar won't exist until MyFunc1 has been run
//and then it will be reset whenever MyFunc1 (a constructor) is run
function MyFunc1(){
MyFunc1.notSoStaticVar = "I belong to MyFunc1";
this.instanceVar = "I belong to instances of MyFunc1";
}
//this code will be run inline one time,
//so the static property of MyFunc2 will exist
//(I like how all the functionality is in one code block, but it's kind of messy)
MyFunc2 = (function(){
var temp = function(){
this.instanceVar = "I belong to an instance of MyFunc2";
}
temp.staticVar = "I belong to MyFunc2";
return temp;
})();
//this seems to be equivalent to MyFunc2, but the code is cleaner
MyFunc3 = function(){
}
MyFunc3.prototype.instanceVar = "I belong to an instance of MyFunc3";
MyFunc3.staticVar = "I belong to MyFunc3";
//tests
console.log(MyFunc1.notSoStaticVar);//undefined!
var a = new MyFunc1();
console.log(MyFunc1.notSoStaticVar);//"I belong to MyFunc1"
console.log(a.instanceVar);//"I belong to instances of MyFunc1"
MyFunc1.notSoStaticVar = "I will be changed when another instance of MyFunc1 is created";
console.log(MyFunc1.notSoStaticVar);//"I will be changed when another instance of MyFunc1 is created"
var b = new MyFunc1();
console.log(MyFunc1.notSoStaticVar);//"I belong to MyFunc1" - was reset by constructor!
//now test MyFunc2
console.log(MyFunc2.staticVar);//"I belong to MyFunc2"
MyFunc2.staticVar = "I am not affected by the construction of new MyFunc2 objects";
var c = new MyFunc2();
console.log(c.instanceVar);//"I belong to an instance of MyFunc2"
console.log(MyFunc2.staticVar);//"I am not affected by the construction of new MyFunc2 objects"
//now test MyFunc3
console.log(MyFunc3.staticVar);//"I belong to MyFunc3"
MyFunc3.staticVar = "I am not affected by the construction of new MyFunc3 objects";
var d = new MyFunc3();
console.log(d.instanceVar);//"I belong to an instance of MyFunc3"
console.log(MyFunc3.staticVar);//"I am not affected by the construction of new MyFunc3 objects"
//interesting
console.log(c);//"temp" <-- not really intuitive!
console.log(d);//"MyFunc3" <-- makes sense
In short: performance.
Defining them inside the function will cause them to be redefined every single time you call the constructor.
While this will behave as expected, it's just overhead for no good reason.
Because that will add unique functions to every object instance. This consumes additional memory overhead that often isn't necessary.
It can be useful in some cases, like when functions should reference local variables, but if that's not the situation, they should be on the prototype.
Also, the static ones will constantly be overwritten.
I have an instance function in javascript and for naming conventions I have other instance function added as property of the first instance function object. It's better illustrated in the following working JavaScript.
var MyModule = (function() { // instance function
return function() {
console.log("ran MyModule");
}
}());
MyModule.RelatedModule = (function() { //second instance function is a property of first instance function object
return function() {
console.log("ran RelatedModule");
}
}())
var inst1 = new MyModule(), // logs "ran MyModule"
inst2 = new MyModule.RelatedModule(); // logs "ran RelatedModule"
This works as intended with no errors. What I'd like to do though is to create the function definition for MyModule after I've created the MyModule object, can anyone help me achieve this? I've illustrated my attempts below.
var MyModule = {}; // create object first, try to set a constructor on it later
MyModule.RelatedModule = (function() { // add properties to the MyModule object
return function() {
console.log("ran RelatedModule");
}
}())
// the following does not work, I'd like to set the `MyModule` constructor instance function and retain the `MyModule.RelatedModule` property
MyModule.constructor = (function() {
return function() {
console.log("ran MyModule");
}
}());
So, how do I retain the properties of an object and change it's constructor?
You're confusing a couple of concepts. In your first example, MyModule doesn't have a constructor, it is a constructor. That is, it's a function object that you intend to use with the new operator to create new objects. Those objects will have a constructor property that points back to MyModule (the function that created them). Changing this constructor property won't have any effect on MyModule; that property is just a pointer back to the function that instantiated the object.
In other words, you can't change MyModule's constructor. That's a meaningless statement.
Now, when you write:
var MyModule = {};
...you create a new object whose constructor property is Object():
console.log(MyModule.constructor) // prints Object()
Again, changing this property doesn't really do much (except obfuscate some useful book-keeping).
At this point MyModule is just a plain-old object. It's not a function at all. That's why you're getting the "not a function" error. Because it's not, but you're trying to use it as though it is. If you want that name to refer to a function (i.e. to a different object) then you're going to lose all references to any properties you previously set, because you're pointing at an entirely new object.
That's just the way it is.
Now, you could save a reference to the object that contains all those previously-set properties and copy them back into MyObject once you've pointed that name at a function. But I'm not sure what the point would be.
Everything lwburk says is correct, however, the below does what you were trying to accomplish, it does this by calling an init() method from MyModule.
var MyModule = function(){
return this.init();
};
MyModule.prototype.init = function(){};
MyModule.RelatedModule = (function() { // add properties to the MyModule object
return function() {
console.log("ran RelatedModule");
};
}());
MyModule.prototype.init = function(){
console.log("ran MyModule");
};
var inst1 = new MyModule(),
inst2 = new MyModule.RelatedModule();
First, there is a known browser bug where the constructor property (of the constructed object) correctly resolves using the prototype, but is not applied in object construction. So you need the following polyfill:
function NEW(clas, ...args)
{
let res = Object.setPrototypeOf({}, clas.prototype);
res.constructor.apply(res, args);
return res;
}
Second, you need to be setting MyModule.prototype.constructor instead of MyModule.constructor. The reason is that MyModule.constructor is the function that constructs new classes, not the function that constructs new objects. (See: Why does a class have a "constructor" field in JavaScript?)
In other words:
var MyModule = {}; // create object first, try to set a constructor on it later
MyModule.RelatedModule = (function() { // add properties to the MyModule object
return function() {
console.log("ran RelatedModule");
}
}())
// set the `MyModule` prototype.constructor instance function and retain the `MyModule.RelatedModule` property
MyModule.prototype = {
constructor() {
console.log("ran MyModule");
}}
var inst1 = NEW(MyModule), // logs "ran MyModule"
inst2 = NEW(MyModule.RelatedModule); // logs "ran RelatedModule"
The short answer is that you can't do that. You can however change the prototype of an object. Check out this answer for insight into how to rethink your approach to work with this constraint: Changing constructor in JavaScript
I'm trying to generate a class from an object in JavaScript. For example:
var Test = {
constructor: function() { document.writeln('test 1'); },
method: function() { document.writeln('test 2'); }
};
var TestImpl = function() { };
TestImpl.prototype.constructor = Test.constructor;
TestImpl.prototype.method = Test.method;
var x = new TestImpl();
x.method();
But this doesn't work: it'll only write 'test 2' (for whatever reason, constructor isn't being defined properly). Why?
I think you're doing it wrong.
Remember, JavaScript doesn't actually have classes at all. It has prototypes instead. So what you're really trying to do is create a prototype object that works like a collection of functions that you've built on another object. I can't imagine any useful purpose for this -- could you elaborate as to what you're trying to do?
Although I think you could make it work by using something like:
var TestImpl = function() {
Test.constructor.apply(this);
};
TestImpl.prototype.method = Test.method;
Your TestImpl function is the constructor. Usually you would do something like this:
var Test1 = function () {
document.writeln('in constructor');
};
Test1.prototype = {
x: 3,
method1: function() { document.writeln('x='+this.x); }
}
var y1 = new Test1();
y1.method1();
y1.x = 37;
y1.method1();
var y2 = new Test1();
y2.method1();
y2.x = 64;
y2.method1();
I think you have things a little backwards. Usually you will assign a prototype to a constructor, rather than assigning a constructor to a prototype.
The reason for assigning a method to the constructor's prototype, rather than to the "this" object inside the constructor, is that the former method creates only 1 shared function, whereas the latter method creates separate instances of a function. This is important (to keep memory allocation to a reasonable amount) if you create lots of objects each with lots of methods.
var Test = function () {
document.writeln('test 1');
this.method = function() { document.writeln('test 2'); }
};
var x = new Test();
x.method();
Javascript doesn't have a "Class" concept, It's all about prototype and the way you use them [ and you can simulate any kind of inheritance with this little neat feature. ]
In javascript "Function" plays the role of [ Class, Method and Constructor ].
so inorder to create "Class" behaviour in Javascript all you need to do is to use the power of "Function".
var A = function(){
alert('A.Constructor');
}
A.prototype = {
method : function(){
alert('A.Method');
}
}
var b = new A(); // alert('A.Constructor');
b.method(); // alert('A.Method');
now the neat thing about JS is that you can easily create "Inheritance" behaviour by using the same method. All you need to do is to connect the second class "Prototype Chain" to the first one, How?
B = function(){
this.prototype = new A(); // Connect "B"'s protoype to A's
}
B.prototype.newMethod = function() { alert('testing'); }
var b = new B();
b.method(); // Doesn't find it in B's prototype,
// goes up the chain to A's prototype
b.newMethod(); // Cool already in B's prototype
// Now when you change A, B's class would automatically change too
A.prototype.method = function(){ alert('bleh'); }
b.method(); // alert('bleh')
If you need any more references I suggest to take a look at Douglas Crockford's Site
Happy JS ing.