Why is this undefined when I call a functions property? - javascript

Here is my code:
function myOuterFunction() {
myInnerFunction();
var myObject = {say: myInnerFunction.myProperty1,
say2: myInnerFunction.myProperty2
};
function myInnerFunction(){
return {myProperty1: "hello",
myProperty2: "world"
};
}
console.log(myObject);
}
myOuterFunction();
Why I am not able to geht the functions property?
I know I could solve this with another variable but why isnt this solution possible?
Thanks

You should store the value of the function before using it.
function myOuterFunction() {
var data = myInnerFunction();
var myObject = {
say: data.myProperty1,
say2: data.myProperty2
};
function myInnerFunction() {
return {
myProperty1: "hello",
myProperty2: "world"
};
}
console.log(myObject);
}
myOuterFunction();

your mistakes are
1) try not to use myInnerFunction() inside myOuterFunction(). it's not a good programming practice
2) calling myInnerFunction() does nothing when calling it out in the open. you are not even giving it's return value to a variable.
3) calling myInnerFunction without () doesn't tell javascript that the it is a function
this is the way you should write it
function myOuterFunction() {
var myObject = {say: myInnerFunction().myProperty1,
say2: myInnerFunction().myProperty2
};
console.log(myObject);
}
function myInnerFunction(){
return {myProperty1: "hello",
myProperty2: "world"
};
}
myOuterFunction();

Related

how do I make a function including a dot

I want to make a function called "lib.hello" is that valid syntax and if not how do I do it?
here us my code function lib.hello(){ console.log("hello") }
function lib.hello(){
console.log("hello")
}
You can do it this way
function yourClass() {
}
yourClass.prototype.dotFunction = function() { return 'hello'; };
console.log(new yourClass().dotFunction());
first you must create an object next you do it same as bellow.
let Obj = {
a:1,
childMethod:(param)=>{console.log(param)}
}
Obj.childMethod("test")
Or you can do it by bellow code:
function yourClass() {
}
yourClass.prototype.childMethod = function(parameter) { console.log(parameter); };
var a = new yourClass();
a.childMethod("test");
//or you can do it same as follow
new yourClass().childMethod("test2")
Why are you asking to do this? This seems like either an XY Problem, or an exercise in theory.
As other answers have alluded to, you can make a class named lib with a method named hello, but that's not quite the same as a function named lib.hello.
Here's another variation:
let a = {
'lib.hello' : function() {
console.log('hello');
}
}
a['lib.hello']()
Technically this is an anonymous function, not a function named lib.hello, but it's kind of what you're asking for because it's associated with the key lib.hello.

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;
}());
}

How to wrap plain function into a constructor?

Is it possible to make a wrapper function MyFunction, which when called with new as in
instance = new MyFunction();
really returns the same object as if the callsite called SomeOtherFunction without new?
instance = SomeOtherFunction();
(I've looked at Proxy but doesn't look like they're supported in Chrome yet.)
Edit:
It turns out the callsite calls MyFunction like this:
var instance = Object.create(MyFunction.prototype);
MyFunction.apply(instance, [/* arguments */]);
// `instance` is supposed to be initialized here
I think this is what you are looking for? Note as Jan Dvorak mentioned, you can only return objects.
function SomeObject() {
return Construct();
}
function Construct() {
return { 'name' : 'yessirrreee' };
}
console.log(new SomeObject())
You can try something like this
function MyClass() {
}
var ob = new MyClass();
Edit after comments
I think this questions needs more context.
I suggest you read about higher order components, but until you've better clarified what exactly you're trying to accomplish, I cannot help you.
I really don't know what your code looks like, but here are some suggestions
either way. My guess nr2 is what you're looking for:
// 1
function MyFunction() {
this.__proto__ = SomeOtherFunction()
}
function SomeOtherFunction() {
return {
foo: function() {
return 'bar'
}
}
}
var fn = new MyFunction()
fn.foo()
// 2
function MyFunction() {}
MyFunction.prototype = SomeOtherFunction()
function SomeOtherFunction() {
return {
foo: function() {
return 'bar'
}
}
}
var fn = new MyFunction()
fn.foo()
// 3
function MyFunction() {}
MyFunction.prototype = SomeOtherFunction.prototype
function SomeOtherFunction() {
function Foo() {}
Foo.prototype.foo = function() {
return 'bar'
}
}
var fn = new MyFunction()
fn.foo()

JavaScript function to edit original object

Is there any way, in JavaScript, to write a function like:
var a = "Hello"
function change(variable, value) {
//Code that edits original variable, not the variable argument
}
alert(a)
change(a, "World!");
alert(a);
And this would output first "Hello", and then "World!". Is there any way to write a function like that?
No, but a close alternative is to treat a as a JS object:
var a = { value : "Hello" };
function change(variable, value) {
//I'll let you work this part out
}
alert(a.value);
change(a, "World!");
alert(a.value);
Here is how you do that by using JavaScript Closures;
var obj = (function() {
var x = 'hello';
return {
get: function() {
return x;
},
set: function(v) {
x = v; }
}
})();
obj.get(); // hello
obj.set('world');
obj.get(); // world
You can only the change the value of the variable using the get and set functions.

How do I chain call functions?

Hey guys am new to javascript app development
When i tried this code
function name() {
return 5;
}
function anotherone() {
return 3;
}
function horse() {
return 5;
}
When i called the function like console.log(name().anotherone().horse()); ..it throws me error like undefined not a function.
Is it possible to call function like afunction().anotherfunction().anotherfunction1() in javascript ??
Thanks in advance..
When you callname().another(), this evaluates to (5).anotherone().
anotherone() is not a function of the literal 5, which is why you get the error undefined is not a function. If you want to chain methods, use a class/object that returns an instance of itself so you can call myClass.aFunction().anotherfunction() so the call stack evaluates to (myClass).anotherfunction()
Yes it is. Every function but the last in the chain have to return the object containing the function you call next, for example:
var obj = {
foo: function(){ return obj; },
bar: function(){ return obj; },
baz: function(){ return 123; }
};
console.log(obj.foo().bar().baz()); // works, logs 123
Read more about OOP in javascript
var Class = function () {};
Class.prototype = {
value: 0,
addOne: function () {
// do stuff
this.value++;
return this;
},
addTwo: function () {
this.value = this.value + 2;
return this;
},
getValue: function () {
return this.value;
}
};
var obj = new Class();
// Chaining possible when you return the object at the end of your method
console.log(obj.addOne().addTwo().addOne().getValue()); // returns 4
// Chaining is not possible when you return something else
console.log(obj.addOne().getValue().addOne()); // undefined is not a function
The problem is your syntax.
Look at your functions: the first returns 5, so you're essentially doing 5.anotherone(). Dot notation is for accessing properties and methods of an object. anotherone() is not a method of 5, so you'll get undefined is not a function.
Also, you don't provide any arguments for the functions, so you can't pass anything to them.
You can kind of do what you're describing, but you have to go about it a bit differently:
function name() {
return 5;
}
function anotherone(num) {
return num + 3;
}
function horse(num) {
return num + 5;
}
console.log(horse(anotherone(name())));
Demo
Its quiet easy:-
function name() {
return 5;
setTimeout(anotherone,0);
}
function anotherone() {
return 3;
setTimeout(horse,0);
}
function horse() {
return 5;
}
Now you just need to call the first function and it will call the next one itself.

Categories

Resources