简体   繁体   中英

Javascript apply not working correctly

Please can you tell me why my .apply() is not working the way I want. What am I doing wrong?

I am expecting

Hi, Alice, I'm Bob

Hi, Steve, I'm Bob

Hi, Mark , I'm Bob

<html>
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <script type="text/javascript">


        var friendlyGreet = function() {


            $.each(arguments, function(index, val) {

                  alert("Hi, " + val.name + ", I'm " + this.name);
            });



        };


        var Bob = {
            name: "Bob"
        };

        var Alice = {
            name: "Alice"
        };

        var Mark = {
            name: "Mark"
        };

        var Steve = {
            name: "Steve"
        };

        friendlyGreet.apply(Bob,[Alice,Steve,Mark]);

        </script>
    </head>
    <body>
    </body>
</html>

The apply is working, but this inside $.each is referring to the element being looped on, and not the main object.

var friendlyGreet = function() {
  var self = this;
  $.each(arguments, function(index, val) {
    alert("Hi, " + val.name + ", I'm " + self.name);
  });
};

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM