hamburger
hamburger

Reputation: 1435

scope issue with function call from object

I need to execute the fc.text-function via fc.messages.max.call( this );

But I do have the error: TypeError: fc is undefined.

The pure fc.text-function works.

I need some explanation with the scopehandling.

Here is the Fiddle

Here is my Code

var fc = {

        methods: { },

        test: function(whatever) {
              console.log("test:", whatever);
            },
        messages: {
            tata: "hello", 
            max: fc.test("Geben Sie bitte einen Wert kleiner oder gleich {0} ein."),
            min: fc.test("Geben Sie bitte einen Wert größer oder gleich {0} ein."),
        },

        otherTest: function() {
                console.log("otherTest works"); 
                fc.test("otherTest");     
                }

   };

fc.test("hello world"); //works
fc.otherTest();         //works also

//fc.messages.max.call( this );

How can i fix this ?

I made another jsfiddle where it works fine. but the function is in a different scope. one more fiddle

Any explanation?

Upvotes: 0

Views: 51

Answers (3)

Rick Lancee
Rick Lancee

Reputation: 1659

From the mdn docs:

The call() method calls a function with a given this value and arguments provided individually.

min: & max: were not functions so you could not call() them.

What calls what:

var test = function( t ) {
    console.log("one more test: ",t);
};
var fc = {
    
    methods: { },
    
    test: function(whatever) {
        console.log("test:", whatever);
    },
    messages: {
        tata: "hello", 
        max: function() { test("var test") },
        min: function() { fc.test("fc test") }
    },
    
    otherTest: function() {
        console.log("otherTest works"); 
        fc.test("otherTest");     
    }
    
};

fc.test("fc test, hello world"); //calls fc.test
test("var test, hello world"); // calls var test
// fc.otherTest();         //works also

fc.messages.max.call( this ); // call var test
fc.messages.min.call( this ); // calls fc.test

http://jsfiddle.net/v7xT6/7/

Upvotes: 1

phylax
phylax

Reputation: 2086

Im not sure, but i think you can't access fc.test() because in messages fc is not complete yet.

compare:

var f = { a: function () { return 1; }, max: f.a() }
> TypeError: Cannot call method 'a' of undefined

It says f is undefined.

You can't access f until the assignment (var f) is complete and f is defined.

Upvotes: 0

pstenstrm
pstenstrm

Reputation: 6489

The call() method is a property of of the Function object.

fc.messages.max isn't a function. It's value is the return value of fc.test(), which is undefined.

Upvotes: 1

Related Questions