I have this function
var x = function outer() {
console.log('outer')
this.inner = function() {
console.log("inner");
}
}
The question is how can I call the inner function outside this scope? I tried x().inner()
but it doesn't work
Your trying to use a type function as a Class try this:
class Outer {
inner () {
console.log("inner");
}
}
console.log(new Outer.inner()) //output inner
here some ref https://www.w3schools.com/js/js_classes.asp
Your outer
function does not return a value.
What happens in your code is that, when you run x()
, it will execute outer
function, which is going to log
something to console, declare this.inner
and exit.
What you need to do is to return this
at the end of outer
function.
Like this:
var x = function outer() {
console.log('outer')
this.inner = function() {
console.log("inner");
}
return this;
}
Then you can do x().inner()
and it will work perfectly!
in the way you do it.
this keyword is pointing to window Object so if you want to call inner you can just
use window.inner();
but if you want to use it as a method you must use new keyword. new keyword create a new object and assine the this keyword to it so inner can be a method for something in my example.
function Outer() { console.log('outer') this.inner = function() { console.log("inner"); } } var something = new Outer(); something.inner();
I can't return this from the outer function, can I access inner function from x variable? - Tarik Ziyad's (OP) comment
If you want to execute only the inner function, you might be for something like this then (or a prototype ):
var outer = function () { this.inner = function() { return 'inner'; } return 'outer'; } outer.prototype.innerProto = function() { return 'inner-proto'; } var x = new outer; console.log(x.inner()); console.log(x.innerProto());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.