I am wondering how to access a function in camera. I have no clue to access function a() and b() from outside. When I run this code, I have undefined error in console.
var camera = (function () {
function a(){
console.log('calling ..a');
}
function b(){
console.log('calling ..b');
}
})();
//calling function a() from outside
camera.a();
I am wondering how to access a function in camera. I have no clue to access function a() and b() from outside. When I run this code, I have undefined error in console.
var camera = (function () {
function a(){
console.log('calling ..a');
}
function b(){
console.log('calling ..b');
}
})();
//calling function a() from outside
camera.a();
Share
Improve this question
asked Nov 18, 2020 at 7:31
user1942626user1942626
8451 gold badge9 silver badges16 bronze badges
3
-
2
Simple answer: you cannot. Not without changing your code to expose
a
. – VLAZ Commented Nov 18, 2020 at 7:32 - You can convert camera to an object and call the functions that way, but is syntax inside an object is slightly different – lharby Commented Nov 18, 2020 at 7:33
-
Simple solution, accept a variable and bleed necessary properties to it. Example:
var someObject = {}; (function(context) { context.a = ...})(someObject)
– Rajesh Commented Nov 18, 2020 at 7:36
5 Answers
Reset to default 4You can return an object, which wraps both the functions:
var camera = (function() {
function a() {
console.log('calling ..a');
}
function b() {
console.log('calling ..b');
}
//exposing a and b as a public API
return {a, b}
})();
//calling function a() from outside
camera.a();
camera.b();
Now you created a private scope for external so you need to create a public scope.
var camera = (function () {
function a(){
console.log('calling ..a');
}
function b(){
console.log('calling ..b');
}
return {
a,
b
}
})();
//calling function a() from outside
camera.a();
The key of that is return the public references of the function.
return {
a,
b
}
function camera(){
this.a=function (){
console.log('calling ..a');
};
this.b=function (){
console.log('calling ..b');
};
}
//calling function a() from outside
var c=new camera();
c.b();
sorry this is ing late... Here's a way to go about it you can follow this link to get a clearer idea and get an idea of what I initially did wrong
const axios = require("axios")
const shitty_code = async (address, number) => {
this.blue = "blue is bright";
this.purple = async () => {
const one_api_call = await axios.get(`https://one-wierd-api/${address}/${number}`).then((response) => {
return response.data })
}
...
return this;
}
// to call the shitty_code method purple ----------------------
console.log(shitty_code("some_random_address", 12).then(async (e)=> {
const response = await e.purple()
console.log(response)
}))
// it actually worked with the this keyword, yay