سؤال

I was playing with private methods and I have accidentally found out, that I can call a method, which calls a private method using ()() - double parentheses instead of assigning it to variables couple of times.

Here is my code to make it clearer:

function Person(name, age) {
    this.name = name;
    this.age = age;
    var bankBalance = 7500;
    var returnBalance = function() {
        return bankBalance;
    };
    this.askTeller = function() {
        return returnBalance;
    }
}

var john = new Person('John', 'Smith', 30);

console.log(john.returnBalance); // undefined

var myBalanceMethod = john.askTeller();
var myBalance = myBalanceMethod();
console.log(myBalance); // 7500

console.log(john.askTeller()()); // 7500 (same result but one line instead of three


So, is that - ()() syntax valid?

هل كانت مفيدة؟

المحلول

Yep it is - john.askTeller() returns the function returnBalance that you then invoke with ().

returnBalance is a function scoped to the Person constructor function, but it is made available outside of this scope when it is returned from the askTeller function call.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top