Function calling error - javascript

Hey guys i am new to javascript app development ..i have did some javascript code but unfortunately it throws some error
The code which i have used is
var c = ( function() { this.name = function() { console.log('yay'); } }());
When i called the instance of the function c it throws error like Uncaught TypeError: undefined is not a function
Why cant i create the instance of function c ??...How can i call the function c so that i can call the inside function name().
Thanx for your help..

Seems you've misunderstood the concept of IIFE. You would need Object
var c = {
name: function() {
console.log('yay');
}
};
c.name(); // yay
But, if you need to go with function, then you would need a Constructor function, which would then be called with a new operator.

Use thisss
var c = function() {
this.name = function() {
console.log('yay');
}
};
newFunction=new c();
newFunction.name()

Since, it is closure, you can not assign to variable var c. If you follow that pattern, you always have to enclose functions/operations inside that (function() {} ).
More on closure- http://javascriptissexy.com/understand-javascript-closures-with-ease/.
To use this, you can modify the js to like this.
var c = (function() {
var name;
function setName(val) {
name = val;
}
return {
print: function() {
setName("yay");
console.log(name);
}
};
})();
console.log(c);
c.print();

Related

JS closure to return object instance as interface

I have the following code.
function Test() {
this.funct_1 = function() {
alert('funct_1');
}
this.funct_2 = function() {
alert('funct_2');
}
return this;}
function getTestObj() {
var testObj;
if (!testObj) {
testObj = new Test();
}
return function() {
return testObj;
}}
What I'm trying to accomplish is the following. I want to have a class Test which is not singleton. Then in some other places in my application I need to have a function which could return the same instance per script execution. I figured that I could use closure for that getTestObj.
However, when I try to use it
getTestObj().funct_1();
I'm getting the following error, saying the funct_1() is not found.
Cannot find function funct_1 in object function () {...}.
Clearly, I'm making some kind of mistake here, but I'm not able to find any solution over the net which could help me. Would appreciate any comments.
NOTE: I'm forced to use ECMA5
testObj is wrapped inside a function
So, either call it
getTestObj()().funct_1(); //notice two ()()
Save the value of getTestObj() in a variable
var singleTon = getTestObj();
var testObj = singleTon();
testObj.funct_1();
Or, simply return testObj (in case singleTon isn't required)
function getTestObj()
{
var testObj;
if (!testObj) {
testObj = new Test();
}
return testObj;
}
And invoke it as
getTestObj().funct_1(); //notice single ()
getTestObj() is returning a function i.e. :
function() {
return testObj;
}
So you have to call it again getTestObj()(), this will return the Test's object and now you can access it's properties.
getTestObj()().funct_1();
OR
You can change your getTestObj function as :
function getTestObj() {
var testObj;
if (!testObj) {
testObj = new Test();
}
return (function() {
return testObj;
}());
}

UnCaught TypeError - Nested objects in Javascript? Why is this not allowed? Object literal notation works

Playing around with some JS tests and I'm trying to instantiate some nested objects in my v namespace. As you'll see below, ClassA and ClassB work as expected. When I try and nest some objects under another property (myCustomProperty) I start running into issues! Could someone explain?
Below is the original code:
var v = (v) ? v : {};
v.someClassA = (function() {
this.hello = function() {
console.log("Class A Hello!");
}
});
v.someClassB = (function() {
this.hello = function() {
console.log("Class B Hello!");
}
});
// this all works!
var myClassA = new v.someClassA();
var myClassB = new v.someClassB();
v.myCustomProperty = (function() {
function someClassC() {
this.hello = function() {
console.log('C');
}
}
function someClassD() {
this.hello = function() {
console.log('D');
}
}
return {
someClassC: someClassC,
someClassD: someClassD
}
});
// Uncaught TypeError: v.myCustomProperty.someClassC is not a function! Why?
var myClassC = new v.myCustomProperty.someClassC();
var myClassD = new v.myCustomProperty.someClassD();
myClassA.hello();
myClassB.hello();
myClassC.hello();
myClassD.hello();
If I change my declaration of v.myCustomProperty to use object literal notation, then it ALL WORKS! :
v.myCustomProperty = {
someClassC: function() {
this.hello = function() {
console.log('C');
}
},
someClassD: function() {
this.hello = function() {
console.log('D');
}
}
}
I guess my question really is how would I make this work using the notation in my original snippet? Possible? Horrible practice to do it that way?
Thanks!
v.myCustomProperty is a function that returns an object. You have to call the function first:
new (v.myCustomProperty().someClassC)();
// ^^
Otherwise, v.myCustomProperty.someClassC() tries to access the property someClassC of the function, and we all know (hopefully) that functions don't have such a property.
Or maybe you intended to execute the function immediately and assign the object to myCustomProperty?
v.myCustomProperty = (function() {
// ...
}()); // <- call function

Call a function of object literal from itself

I tried execute this code:
var system = new Object();
(function($) {
$.init = function() {
var o = {
message: function(arg) {
return arg.val;
},
alert: this.message({
val: "Hello, world."
})
};
return o.alert;
};
})(system);
alert(system.init());
but, when I execute it I get error message which tells me that this.message is not a function. Obviously, this not refers to object o itself, and I want to know why.
I found few solutions on stackoverflow where this is always inside function body, but why this can not be outside? Thanks.
Change your code to:
var system = new Object();
(function($) {
$.init = function() {
var o = {
message: function(arg) {
return arg.val;
}
};
o.alert = o.message({
val: "Hello, world."
});
return o.alert;
};
})(system);
system.init()
Yields:
"Hello, world."
In your code this would refer to window in that context. If you want to create an object and refer to it as this - use constructor function, i.e.:
var o = new function(){
...
<here: this == o>
...
}
You can use an anonymous constructor function instead of object literal syntax if you want to reference the object during instantiation.
(function($) {
$.init = function() {
// -----vvv---vvv---constructor function
var o = new function() {
this.message = function(arg) {
return arg.val;
},
this.alert = this.message({
val: "Hello, world."
})
};
return o.alert;
};
})(system);
Because the value of this is only defined within a function when the function is invoked, object literal syntax never changes its value.
So instead we create a function, and invoke it using new so that the value of this in the function is a reference to the new object we're building.
And of course it doesn't need to be anonymous, but if you're only going to use it once, there's no need for a name.

variable in my javascript class is undefined when using an instance of that class

I have declared this javascript class:
var TablixColumns = function(){
this.g = 'wtf';
this.tablixColumns = []; //[];
return {
addTablixColumn: function(tablixColumn){
alert(this.g);
//this.tablixColumns.push(tablixColumn.getTablixColumn());
}
}
};
my problem is that when I try this: alert(this.g) the alert comes out undefined
of course my initial function definition read: this.tablixColumns.push(tablixColumn.getTablixColumn());
but then I get the error that reads something like "No Method push of undefined"
what's weird is I have this class declaration:
var TablixColumn = function(){
columnWidth = '<Width>3.135cm</Width>'; //default width value
return{
setColumnWidth: function(width){
this.columnWidth = '<Width>' + width + 'cm</Width>';
},
getTablixColumn: function(){
return '<TablixColumn>' + this.columnWidth + '</TablixColumn>';
}
}
};
and the TablixColumn class works fine,
and yes, I have declared this.g and this.tablixColumns without the 'this.' part, but it's just refusing to work!
I'm going to kill someone if this doesn't work tonight can someone help me please?
You need to set a reference to the current object (this) outside the nested function expression. Here's how your code should look:
var TablixColumns = function() {
...
var self = this;
return {
addTablixColumn: function(tablixColumn) {
alert(self.g);
}
};
};
You can even set a property to the returned object literal if you want:
// ...
return {
g: 'wtf',
addTablixColumn: function(tablixColumn) {
alert(this.g); // 'wtf'
}
};
// ...
Note that you shouldn't use TablixColumns as a constructor if you're returning from it like this. You're using two idioms here; prototypal inheritance and the module pattern. Are you going to instantiate the constructor with new? If so, then don't return the object literal. Rather, set the methods on the prototype of the function:
var TablixColumns = function() {
this.g = 'wtf';
this.tablixColumns = [];
};
TablixColumns.prototype.addTablixColumn = function addTablixColumn() { ... };
TablixColumns.prototype./* ... */
...
Otherwise, don't use this inside the constructor. Simply make the properties normal variables.
Okay guys so I figured out my problem:
all the references to variables of the current instance should not have been preceded by the this. keyword
so this is how my declaration looks now:
var TablixColumns = function(){
g = 'wtf';
tablixColumns = []; //[];
return {
addTablixColumn: function(tablixColumn){
alert(g);
tablixColumns.push(tablixColumn.getTablixColumn());
}
}
};
Thanks #Bergi for pointing this out

OOP prototype.method call this.method

var fn = function() {
this.method1 = function() {
return this.public;
};
this.method2 = function() {
return {
init: function() { return this.public; }
}
};
fn.prototype.public = "method prototype";
};
create object fn
var object = new fn();
object.method1() // "method prototype"
object.method2().init(); // undefined
this.public Prototype in method2().init() function run return undefined ?
Is there an alternative to Prototype?
thank you.
The issue is related to the different scope in which this is bound on init function of method2(), so try this:
this.method2 = function() {
var self = this;
return {
init: function() { return self.public; }
}
};
so
object.method2().init(); // return "method prototype"
There is a lot wrong with this.
But the direct answer to your specific question is that calling init returns undefined because its reference to this is to the inner object that you've created and not the instance that you think it refers to.
I suggest you stop trying to solve this particular problem and learn the basics of prototypal inheritance in JavaScript
This this in the init function is the object returned by object.method2(), which has no public property on it.

Categories

Resources