1

i'm trying to create a JavaScript object named human with three methods walk, eat and talk, and i want to call it like this (no method should print any values): human.talk('hello').walk('home').eat('pizza').

I have this code:

var human = {
    talk : function talk(t){

    },
    walk : function walk(w){

    },
    eat : function eat(e){

    }
};

console.log(human.talk('hello').walk('home').eat('pizza'));

But i'm receiving Uncaught TypeError: Cannot call method 'walk' of undefined

Why??

2
  • Like this jsfiddle.net/ccHGF :P Commented Oct 8, 2013 at 0:35
  • 1
    Does talk return the human? It has to for chaining to work. Commented Oct 8, 2013 at 0:59

3 Answers 3

6

Each function needs to return this if you want to be able to chain functions. You are getting the error because the function talk is returning undefined and you are essentially trying to call undefined.walk('home').

Sign up to request clarification or add additional context in comments.

Comments

0

You cannot just chain calls like that. Did you mean to log all three results?

console.log(human.talk('hello'),human.walk('home'),human.eat('pizza'));

If you did want to have a "fluent" call chain, your functions all need to return this (so that you can proceed to call functions on it).

Comments

0

its not exactly clear what you are trying to achieve with the code above but from what I can see, there are two options:

A. you are trying to call all three functions and have console.log print the results of the functions in sequence, one after the other, ie you are using the (.) operate to concatenate the results of the function calls into one long string, in this case i would like to remind you that the concatenation operator in javascript, unlike, say php is + and not (.) so rather use this:

console.log(human.talk('hello') + walk('home') + eat('pizza'));

B. You actually want to call a chain for function calls. in which case i would like to remaind you that the . operator retrieves a property or method of an object ie the syntax is (object).(property), always the identifier or value before the operator should be an object. So, in order for you chain call to work, all your given function should return an object,(well, maybe except for the last one) in this case, the appropriate return value would be "this":

var human = {
    talk : function(t){
       return this;

    },
    walk : function(w){
       return this;
    },
    eat : function(e){
       return this;//or whatever here
    }
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.