I'm trying to train myself to write chaining function but got error of
Cannot read property 'minus' of undefined(…)
What's wrong with my code?
var math = function(){ var result = 0; var add = function(param){ result += param; }; var minus = function(param){ result -= param; }; var print = function(){ console.log(result) }; return {add:add, minus: minus, print:print}; } var calculator = math(); var result = calculator.add(5).minus(1).print(); console.log(result)
You need to return the object ( this
) in this case, to "chain" like you are expecting
You print()
also doesn't return anything so result
is always undefined.
var math = function(){ var result = 0; var add = function(param){ result += param; return this; }; var minus = function(param){ result -= param; return this; }; var print = function(){ console.log('result: ' + result); // print doesnt return anything, it needs to if you want to assign anything by calling it return result; }; return {add:add, minus: minus, print:print}; } var calculator = math(); var result = calculator.add(5).minus(1).print(); console.log(result)
You can also store a reference to the object returned.
var math = function() { var result = 0; var add = function(param) { result += param; return math; }; var minus = function(param) { result -= param; return math; }; var print = function() { console.log(result) }; var math = { add: add, minus: minus, print: print }; return math; } var calculator = math(); calculator.add(5).minus(1).print();
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.