0

Why is the call to alert() popping up undefined? I'm guessing that Javascript's not using the this that I think it is. How can I fix the code while still making it read somewhat like non-prototypal inheritance code?

<!DOCTYPE html>
<html>
    <head><title>Help</title>
        <script type="text/javascript">

            var Foo = function (myName) {
                this.myName = myName;
            }

            Foo.prototype.sayName = function () {
                alert(this.myName);

            }

            var foo = new Foo("I am foo");

            var bar = {
                ask: function (fn) {
                    fn();
                }
            };

            function doIntroductions() {
                bar.ask(foo.sayName);
            }

        </script>
    </head>
    <body onload="doIntroductions();">
    </body>
</html>
CL22
  • 13,696
  • 23
  • 83
  • 147

1 Answers1

2

this depends on how you call the function. You are calling the function in the context of the global object, where no property sayName exists. You need to set the context explicitly:

bar.ask(foo.sayName.bind(foo));

bind makes sure that this inside of sayName is foo when you call fn.

elclanrs
  • 85,039
  • 19
  • 126
  • 159